Skip to content
Advertisement

Java XML: how to get attribute value as NULL if not present?

Java XML: how to get attribute value as NULL if not present?

<foo name="A"/>

elementFoo.getAttribute("value");  // return empty string

It returns empty string. Is there a way to get the value as NULL? It is easy to convert it. But we have hundreds of places like this, and it would be great if XML parser support it. Is there a way to configure XML parser?

Advertisement

Answer

AFAIK, Element#getAttribute will always return an empty String if the attribute does not have a specified or default value.

From Oracle documentation:

public String getAttribute(String name)
...
Returns: The Attr value as a string, or the empty string if that attribute does not have a specified or default value.

But you can use Element#getAttributeNode instead, it will return null if the attribute does not exist. https://docs.oracle.com/cd/A97339_01/doc/xml/parser/oracle.xml.parser.v2.XMLElement.html#getAttributeNode(java.lang.String)

Later, you can use Attr#getValue() to retrieve the value. https://docs.oracle.com/cd/A97339_01/doc/xml/parser/org.w3c.dom.Attr.html#getValue()

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement