XML file containing multiple root elements

前端 未结 3 1280
青春惊慌失措
青春惊慌失措 2021-01-15 14:13

I have a file which contains multiple sets of root elements. How can I extract the root element one by one?

This is my XML


    

        
3条回答
  •  一整个雨季
    2021-01-15 14:39

    Use java.io.SequenceInputStream to trick xml parser:

    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

提交回复
热议问题