How can I check if a specific child dose not exist in XML using Java Dom in the following sample: I am looking for all userFiled occurrences and in the first part, there are none. So I want to say if there is no tag userField do something.
4
Function organisation unit combination 1
4
Function organisation unit combination 1
3.0
N.A.
something like:
NodeList NodeuserField = element.getElementsByTagName("userField");
Element line;
for (int j = 0, l = NodeuserField.getLength(); j < l; j++) {
line = (Element) NodeuserField.item(j);
for (Entry userFieldUserDef : map_userField.entrySet()) {
if (element.getElementsByTagName("hash") == null) {
//Do Something
}
}
}
解决方案
Just like in this question I suggest using XPath again. You can do it via the Java XPath API (which sucks), or again use data projection (Yes, I'm affiliated with this project). There are several possibilities to determine via XPath if an element exist. You could just try to read it and test if the result is null. Here as an alternative: Declaring directly a boolean projection method:
public class ElementExists {
public interface Projection {
interface Element {
@XBRead("./@hash")
String getHash();
@XBRead("count(./userField)>0")
boolean hasUserField();
}
@XBRead("//element")
List getElements();
}
public static void main(final String[] args) throws IOException {
Projection projection = new XBProjector().io().url("resource://data.xml").read(Projection.class);
for (Projection.Element e : projection.getElements()) {
System.out.print("Element with hash '" + e.getHash() + "' has ");
System.out.println((e.hasUserField() ? "" : "no ") + "user field");
}
}
}
This program prints out
Element with hash 'AOK_1416092142370_76' has no user field
Element with hash 'AOK_1417643334024_77' has user field