【问题标题】:Java XML: how to get attribute value as NULL if not present?Java XML:如果不存在,如何将属性值设为 NULL?
【发布时间】:2022-01-18 02:06:07
【问题描述】:

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

<foo name="A"/>

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

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

【问题讨论】:

    标签: java xml xml-parsing


    【解决方案1】:

    AFAIK,如果属性没有指定或默认值,Element#getAttribute 将始终返回 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 代替,如果该属性不存在,它将返回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()

    【讨论】:

      猜你喜欢
      • 2015-09-06
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多