开发者

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

开发者 https://www.devze.com 2023-01-26 17:14 出处:网络
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 wi

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开发者_如何学C 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消