java 如何将 InputStream 转换为 InputSource?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17118585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:03:11  来源:igfitidea点击:

How to convert InputStream to InputSource?

javaxmlinputstreamsax

提问by Igor

ALL,

全部,

I wrote a simple SAX XML parser. It works and I was testing it with local XML file. Here is my code:

我写了一个简单的 SAX XML 解析器。它有效,我正在使用本地 XML 文件对其进行测试。这是我的代码:

SAXParserFactory spf = SAXParserFactory.newInstance();
XMLParser xmlparser = null;
try
{
    SAXParser parser = spf.newSAXParser();
    XMLReader reader = parser.getXMLReader();
    xmlparser = new XMLParser();
    reader.setContentHandler( xmlparser );
    reader.parse( new InputSource( getResources().openRawResource( R.raw.categories ) ) );

Now I need to read this XML file from the website. The code I'm trying is:

现在我需要从网站读取这个 XML 文件。我正在尝试的代码是:

public InputStream getXMLFile()
{
    URL url = new URL("http://example.com/test.php?param=0");
    InputStream stream = url.openStream();
    Document doc = docBuilder.parse(stream);
}
reader.parse( new Communicator().getXMLFile() );

I'm getting compiler error

我收到编译器错误

"The method parse(InputSource) is not applicable for the argument (InputStream)".

“方法解析(InputSource)不适用于参数(InputStream)”。

I need help figuring out what do I need.

我需要帮助弄清楚我需要什么。

Thank you.

谢谢你。

回答by Jon Skeet

While I hate to sound obvious, is there any reason you're not using this constructor?

虽然我不想听起来很明显,但你有什么理由不使用这个构造函数吗?

InputSource source = new InputSource(stream);
Document doc = docBuilder.parse(source);

Note that that's very similar to what you're doing in the first section of code. After all, openRawResourcereturns an InputStreamas well...

请注意,这与您在第一部分代码中所做的非常相似。毕竟,openRawResource返回一个InputStream......