简体   繁体   中英

Java - parse xml string with variable tagnames?

I'm trying to parse an XML string, and the tagnames are variable; I haven't seen any examples on how to pull the information out without knowing them. For example, I will always know the <response> and <data> tags below, but what falls inside/outside of them could be anything from <employee> to you name it.

    <?xml version="1.0" encoding="UTF-8"?>

     <response> 
        <generic>
           ....
        </generic>   
        <data>
             <employee>
                <name>Seagull</name>
                <id>3674</id>
                <age>34</age>
             </employee>
             <employee>
                <name>Robin</name>
                <id>3675</id>
                <age>25</age>
             </employee>
       </data>
   </response>

You could parse it into a generic dom object and traverse it. For example, you could use dom4j to do this.

From the dom4j quick start guide:

public void treeWalk(Document document) {
    treeWalk( document.getRootElement() );
}

public void treeWalk(Element element) {
    for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
        Node node = element.node(i);
        if ( node instanceof Element ) {
            treeWalk( (Element) node );
        }
        else {
            // do something....
        }
    }
}

public Document parse(URL url) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(url);
    return document;
}

I have seen similar situation in the projects.

If you are going to deal with large XMLs, you can use Stax or Sax parser to read the XML. On every step (like on reaching end element), enter the data into a Map or a dta structure of your choice, where you keep tag names as the key and value as value in the Map. Finally once you have the parsing done, use this Map to figure out which object to build as finally you would have a proper entity representation of the information in the XML

If XML is small,use DOM and directly build the entity object by reading the specific tag (like employee> or use XPATh to where you expect the tag to be present, giving you hint of the entity. Build that object directly by reading the specific information from the XML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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