4

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

<Person>
    <empid></empid>
    <name></name>
</Person>
<Person>
    <empid></empid>
    <name></name>
</Person>
<Person>
    <empid></empid>
    <name></name>
</Person>

How can I extract one set of Person at a time?

Alex P.
  • 30,437
  • 17
  • 118
  • 169
Gopal2311
  • 41
  • 1
  • 1
  • 2
  • Your tag says "java", but it's not very obvious if you are looking for a library or a code solution. This question gets very broad... – firelynx Jun 22 '15 at 15:48
  • 3
    This is not a valid XML document. – laune Jun 22 '15 at 15:50
  • Valid xml file can't contain more than one root. But you have some options here: 1. Enclose your xml code into element and parse it via common java lib code (e.g. DocumentBuilder) 2. Read as text, enclose into tag and fallback to (1). 3. Parse it manually. – korifey Jun 22 '15 at 15:51
  • Laune and korifey, yes, but you mean [***well-formed***, not *valid*](http://stackoverflow.com/a/25830482/290085). – kjhughes Jun 22 '15 at 16:08
  • will you please help me in that how can I append a root element for this xml file via code. – Gopal2311 Jun 23 '15 at 09:14

3 Answers3

10

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<InputStream> streams = Arrays.asList(
                new ByteArrayInputStream("<root>".getBytes()),
                new FileInputStream("persons.xml"),
                new ByteArrayInputStream("</root>".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<children.getLength(); i++){
            Node child = children.item(i);
            if(child.getNodeType()==Node.ELEMENT_NODE){
                System.out.println("persion: "+child);
            }
        }
    }
}
Santhosh Kumar Tekuri
  • 3,012
  • 22
  • 22
3

You cannot parse your file using an XML parser because your file is not XML. XML cannot have more than one root element.

You have to treat it as text, repair it to be well-formed, and then you can parse it with an XML parser.

Community
  • 1
  • 1
kjhughes
  • 106,133
  • 27
  • 181
  • 240
-1

If your XML is valid, using a SAX or DOM parser. Please consult the XML Developer's Kit Programmer's Guide for more details.

dan
  • 13,132
  • 3
  • 38
  • 49