开发者

XML parsing Complexity

<root>
    <nodes>
        <headnode>
            <info>Sometext1</info>
        </headnode>
        <leafnode>
            <info>sometext2</info>
        </leafnode>
        <leafnode>
            <info>sometext3</info>
        </leafnode>
    </nodes>

    <nodes>
        <headnode>
            <info>Sometext4</info>
        </headnode>
        <leafnode>
            <info>sometext5</info>
        </leafnode>
        <leafnode>
            <info>sometext6</info>
        </leafnode>
    </nodes>
</root>

I have the above Document to parse in the server side inside a JavaBean. I have to extract the <info> from the <headnode> of every children.

I have tried to parse this with Java DOM but I cant get into the sublevels of the tree using

NodeList nList = doc.getElementsByTagName("nodes");
开发者_运维百科

But I cant iterate further down and unable to retrieve ... from each <headnode> of every <nodes> tag. Please help.


This will get the <info> text from every <headnode> in your XML:

NodeList nodeList = doc.getElementsByTagName("headnode");
for (int i = 0; i < nodeList.getLength(); i++) {
    Node node = nodeList.item(i);
    NodeList childList = node.getChildNodes();
    for (int j = 0; j < childList.getLength(); j++) {
        Node childNode = childList.item(j);
        if (childNode.getNodeName().equals("info")) {
            String info = childNode.getTextContent();
            System.out.println(info);
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜