javaxmldom4j

Checking wether attribute is present while parsing xml


Hi I am working with code that parses xml

<a>
  <n>SomeVal</n>
  <c oldval="1">2</c>
<a>

The java code that parses the xml, uses dom4j (valueOf) to parse the values of the tags supplying xpath expressions. Its possible to get the oldval attribute by using an xpath expression like "c/@oldval". The issue I am trying to figure out is how I can tell wether an attribute is present. Since I need to distinguish between the case where oldval attribute is not present and the one where it is present and is blank. Both the xml's below would return the same value for oldval.

<a>
  <n>SomeVal</n>
  <c>2</c>
<a>

And

<a>
  <b>SomeVal</b>
  <c oldval="">2</c>
<a>

Solution

  • you can either check for the case with containing attribute via XPath:

    /a/c[@oldval]
    

    this will return you the case if oldval attribute is present. If not, check again with if the node is existent

    /a/c
    

    Alternatively, you fetch for the node first

    /a/c
    

    and you check now if the contains the attribute with

    Element element = (Element) node;
    String oldvalStr = element.attributeValue("oldval");
    

    You can also do the test fully in xpath, but would not suggest you, since the java code is pretty easy to understand to all developers