Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a tag contains a value or another tag?

Tags:

java

dom

xml

I am using DOM representations in java

how can I distinguish if an xml tag has a value inside it or has another embedded tag ? For example, I can have :

<item> 2 </item>

or

<item> <name> item1 </name> </item>

i want to do the following

if(condition1 : there is no tags inside item tag) do ...
else  do ...

how can I write condition 1 ?

like image 848
SLA Avatar asked Jul 10 '11 13:07

SLA


1 Answers

You can just test every child by iterating over the list of child nodes:

public static boolean hasChildElements(Element el) {
    NodeList children = el.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
            return true;
        }
    }
    return false;
}

condition1 is then (! hasChildElements(el)).

Alternatively, you can implement the test with getElementsByTagName("*").getLength() == 0. However, if there are sub elements, this method will traverse the whole fragment you're testing, and allocate lots of memory.

like image 144
phihag Avatar answered Oct 11 '22 14:10

phihag