Java XML:如果不存在,如何将属性值设为 NULL?

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

Java XML: 如果不存在,如何将属性值设为 NULL?

<foo name="A"/>

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

它returns 空字符串。有没有办法将值设为 NULL?转换它很容易。但是我们有数百个这样的地方,如果 XML 解析器支持它就太好了。有没有办法配置 XML 解析器?

AFAIK,如果属性没有指定值或默认值,Element#getAttribute 将始终 return 和 empty String

来自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.

但是您可以使用Element#getAttributeNode代替,如果该属性不存在,它将return nullhttps://docs.oracle.com/cd/A97339_01/doc/xml/parser/oracle.xml.parser.v2.XMLElement.html#getAttributeNode(java.lang.String)

稍后,您可以使用 Attr#getValue() 检索值。 https://docs.oracle.com/cd/A97339_01/doc/xml/parser/org.w3c.dom.Attr.html#getValue()