简体   繁体   English

如何使用Java的SAX Parser从URL数组一次解析多个XML feed?

[英]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. 我正在使用一个Android应用程序,该应用程序根据用户首选项分析一个或多个XML提要。 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? 通过为解析器提供XML提要的URL数组,是否可以一次解析(使用SAX解析器)多个XML提要?

If no, what would be an alternative way of listing the parsed items from different XML feeds in one list? 如果不是,那么将来自不同XML提要的已解析项目列出在一个列表中的另一种方法是什么? An intuitive approach is to use java.io.SequenceInputStream to merge the two input streams. 一种直观的方法是使用java.io.SequenceInputStream合并两个输入流。 However, this throws a NullPointerException: 但是,这将引发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. 在解析之前附加流的策略不太可能很好地工作,因为附加的XML将不是有效的XML。 As each XML input has its own root element, the appended XML will have multiple roots, which is not permitted in XML. 由于每个XML输入都有其自己的根元素,因此附加的XML将具有多个根,这在XML中是不允许的。 Additionally it's likely to have multiple XML headers like 另外,它可能具有多个XML标头,例如

<?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. 可以使SAX解析器将已解析的元素添加到现有的元素列表中。 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. 如果您在问题中张贴代码以显示如何解析单个文件,我们也许可以帮助您确定如何根据您的多个输入需求进行调整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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