简体   繁体   中英

How to parse multiple XML feeds at once from an array of URLs with SAX Parser for Java?

I am working on an Android application that parses one or more XML feeds based on user preferences. Is it possible to parse (using SAX Parser) more than one XML feed at once by providing the parser with an array of URLs of my XML feeds?

If no, what would be an alternative way of listing the parsed items from different XML feeds in one list? An intuitive approach is to use java.io.SequenceInputStream to merge the two input streams. However, this throws a NullPointerException:

try {
  URL urlOne = new URL("http://example.com/feedone.xml");
  URL urlTwo = new URL("http://example.com/feedtwo.xml");
  InputStream streamOne = urlOne.openStream();
  InputStream streamTwo = urlTwo.openStream();
  InputStream streamBoth = new SequenceInputStream(streamOne, streamTwo);
  InputSource sourceBoth = new InputSource(streamBoth);
  //Parsing
  stream = xmlHandler.getStream();
  }
catch (Exception error) {
  error.printStackTrace();
}
List<Item> content = stream.getList();
return content;

The tactic of appending the streams before parsing is not likely to work well, as the appended XML will not be valid XML. As each XML input has its own root element, the appended XML will have multiple roots, which is not permitted in XML. Additionally it's likely to have multiple XML headers like

<?xml version="1.0" encoding="UTF-8"?>

which is also invalid.

While it's possible to preprocess the input to work around these issues, you're likely better off parsing them separately and dealing with getting the results combined later.

It's possible to make a SAX parser add the parsed elements to an existing list of elements. If you post code in your question showing how you're parsing a single file, we might be able to help figure out how to adjust it to your need for multiple inputs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM