gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:50:27 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com