How to convert InputStream to InputSource?
Asked Answered
S

1

6

ALL,

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

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:

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)".

I need help figuring out what do I need.

Thank you.

Spinule answered 14/6, 2013 at 23:13 Comment(0)
E
15

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...

Endrin answered 14/6, 2013 at 23:15 Comment(1)
If you use JUST stream as source, then the parser has no information about where the stream came from. If you construct the source from URL then it can use this information to construct URLs of referenced documents. For example if you enable XInclude and your XML stream contains <xi:include href="other.xml"/> then if you are parsing strem the parser can't resolve the other.xml. But if you create source from URL it can dereference other.xml and include it's content in parsed entity.Hadley

© 2022 - 2024 — McMap. All rights reserved.