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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With