包含多个根元素的XML文件

我有一个包含多组根元素的文件。 如何逐个提取根元素?

这是我的XML

            

我怎样才能一次提取一组Person

使用java.io.SequenceInputStream来欺骗xml解析器:

 import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilderFactory; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.io.SequenceInputStream; import java.util.Arrays; import java.util.Collections; import java.util.List; public class MultiRootXML{ public static void main(String[] args) throws Exception{ List streams = Arrays.asList( new ByteArrayInputStream("".getBytes()), new FileInputStream("persons.xml"), new ByteArrayInputStream("".getBytes()) ); InputStream is = new SequenceInputStream(Collections.enumeration(streams)); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is); NodeList children = doc.getDocumentElement().getChildNodes(); for(int i=0; i 

您无法使用XML解析器解析文件,因为您的文件不是XMLXML不能有多个根元素。

您必须将其视为文本,将其修复为格式良好 , 然后您可以使用XML解析器对其进行解析。

如果您的XML有效,请使用SAX或DOM解析器。 有关更多详细信息,请参阅XML Developer’s Kit程序员指南 。