java - XML 中的 TextContent 和属性值之间的区别

标签 java xml attributes

属性的getTextContent()getValue()之间有区别吗?

在以下情况下,它会将相同的内容打印到控制台中。 我已经发现 getNodeValue()getValue 是相同的(根据 http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Node.html#getNodeValue() )。

XML:

<Request w="4.2">

代码:

getString("Request", rootElement);

void printAtt(String tagName, Element element) {
        NodeList list = element.getElementsByTagName(tagName);
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            Element nodeElement = (Element) node;
            Attr attribute = nodeElement.getAttributeNode("w");
            System.out.println("ATTR NAME: " + attribute.getName());
            System.out.println("ATTR TEXT CONTENT: " + attribute.getTextContent());
            System.out.println("ATTR VALUE: " + attribute.getValue());
            System.out.println("ATTR NODE VALUE: " + attribute.getNodeValue());
        }
}

输出为:

ATTR NAME: w
ATTR TEXT CONTENT: 4.2
ATTR VALUE: 4.2
ATTR NODE VALUE: 4.2

最佳答案

有一个至关重要的区别。 getTextContent()将连接其节点及其后代(如果有)的所有文本内容并返回值 while getNodeValue()将返回其当前节点的值。

Javadoc 指出,getNodeValue():

The value of this node, depending on its type; see the table above. When it is defined to be null, setting it has no effect, including if the node is read-only.

getTextContent():

This attribute returns the text content of this node and its descendants. When it is defined to be null, setting it has no effect. On setting, any possible children this node may have are removed and, if it the new string is not empty or null, replaced by a single Text node containing the string this attribute is set to. On getting, no serialization is performed, the returned string does not contain any markup. No whitespace normalization is performed and the returned string does not contain the white spaces in element content (see the attribute Text.isElementContentWhitespace). Similarly, on setting, no parsing is performed either, the input string is taken as pure textual content. The string returned is made of the text content of this node depending on its type.

对于 ATTRIBUTE_NODE,两个函数的值相同,因为属性没有后代,因此您会收到相似的结果。

关于java - XML 中的 TextContent 和属性值之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30985296/

相关文章:

asp.net-mvc - 允许 EmailAddressAttribute 为空字符串

java - JAX-RS 如何以带有字段名称的 Json 形式返回列表

vue.js - Vue点击按钮时改变属性值的方法

html - 非标准属性有什么用?

java - JAXB 解码返回属性的 null

php - 每分钟运行一次 cronjob 的风险

android - 如何在android中获取动画?

Java - Sonar - 不应使用循环复制数组

java - AsyncTask 在第一行之后崩溃?

java - 从每个窗口在 Eclipse 中打开 Type (Ctrl+Shift+T)