属性的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/