user1932034
user1932034

Reputation: 149

How get tag value using DOM parser

I use dom parser in my app. So. i have next situation:

XML:

<test>
    <A>
      <B>hello</B>
    world
    </A>
</test>

Code:

private TagA parseTagA(Node node) {
        TagA tagA = new TagA();
        if (node.hasChildNodes()) {
            NodeList childList = node.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                // gets child
                Node child = childList.item(i);
                // parse <B> tag
                if (child != null && "B".equals(child.getNodeName())) {
                   tagA.setTagB(parseTagB(child));
                }
            }
        }

        String tagABody = node.getTextContent();
        tagA.setBody(tagABody);


        return tagA;
    }

I use node.getTextContent() method to get value of tag A, but i get value of tag B too. I mean what value of "tagABody" is"hello world", but should be just "world". Method getNodeValue() return null, i guess because node type is ELEMENT_NODE. Anyway i have question:How i can get value only of tag A, only "world" ? Thanks.

Upvotes: 0

Views: 1966

Answers (2)

Mubin
Mubin

Reputation: 4239

I didn't test it, but I believe the below code should work:

private TagA parseTagA(Node node) {
    TagA tagA = new TagA();
 String tagABody  = "";
    if (node.hasChildNodes()) {
        NodeList childList = node.getChildNodes();
        for (int i = 0; i < childList.getLength(); i++) {
            // gets child
            Node child = childList.item(i);
        if(child.getNodeType == Node.TEXT_NODE) {
           tagABody = node.getNodeValue();
           tagA.setBody(tagABody);
            } else
            // parse <B> tag
            if (child != null && "B".equals(child.getNodeName())) {
               tagA.setTagB(parseTagB(child));
            }
        }
    }


    return tagA;
}

Upvotes: 1

Arthur Dent
Arthur Dent

Reputation: 795

I suggest processing the text node children of the A element.

You can do this in the loop of child nodes that you are doing anyway. The if that identifies tag B for you would have an else, in which you would accumulate the non-B text.

Upvotes: 0

Related Questions