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
How to convert InputStream to InputSource?
提问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, openRawResource
returns an InputStream
as well...
请注意,这与您在第一部分代码中所做的非常相似。毕竟,openRawResource
返回一个InputStream
......