parse xml using dom java

Jimmysnn

I have the bellow xml:

<modelingOutput>
    <listOfTopics>
        <topic id="1">
            <token id="354">wish</token>
        </topic>
    </listOfTopics>
    <rankedDocs>
        <topic id="1">
            <documents>
                <document id="1" numWords="0"/>
                <document id="2" numWords="1"/>
                <document id="3" numWords="2"/>
            </documents>
        </topic>
    </rankedDocs>
    <listOfDocs>
        <documents>
            <document id="1">
                <topic id="1" percentage="4.790644689978203%"/>
                <topic id="2" percentage="11.427632949428334%"/>
                <topic id="3" percentage="17.86913349249596%"/>
            </document>
        </documents>
    </listOfDocs>
</modelingOutput>

Ι Want to parse this xml file and get the topic id and percentage from ListofDocs

The first way is to get all document element from xml and then I check if grandfather node is ListofDocs. But the element document exist in rankedDocs and in listOfDocs, so I have a very large list.

So I wonder if exist better solution to parse this xml avoiding if statement?

My code:

public void parse(){
    Document dom = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xml));

    dom = db.parse(is);

    Element doc = dom.getDocumentElement();
    NodeList documentnl = doc.getElementsByTagName("document");
    for (int i = 1; i <= documentnl.getLength(); i++) {
        Node item = documentnl.item(i);
        Node parentNode = item.getParentNode();
        Node grandpNode = parentNode.getParentNode();
        if(grandpNode.getNodeName() == "listOfDocs"{
            //get value
        }
    } 
}
M A

First, when checking the node name you shouldn't compare Strings using ==. Always use the equals method instead.

You can use XPath to evaluate only the document topic elements under listOfDocs:

XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
XPathExpression xPathExpression = xPath.compile("//listOfDocs//document/topic");

NodeList topicnl = (NodeList) xPathExpression.evaluate(dom, XPathConstants.NODESET);
for(int i = 0; i < topicnl.getLength(); i++) {
   ...

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related