简体   繁体   English

XML节点和子节点

[英]XML Node and Child Nodes

header = new LinkedHashMap<String,Object>();
Element headerElement = (Element)doc.getElementsByTagName( "Header").item(0);
NodeList elementList = headerElement.getElementsByTagName( "*" );
for( int index =0; index < elementList.getLength(); index++ ){
    Node element = elementList.item(index);
    System.out.println( element.getChildNodes().item(0).getTextContent() ); // Statement A          
    System.out.println( element.getTextContent()); // Statement B

Both Statement A and Statement B are printing the same output. 语句A和语句B都打印相同的输出。

What does it means, every node is a child node for itself?? 这是什么意思,每个节点本身就是一个子节点??

And the input XML is 输入的XML是

<Header>
    <tag1>1</tag1>
    <tag2>2</tag2>
    <tag3>3</tag3>
    <tag4>4</tag4>
</Header>

From the documentation of Node.getTextContent() , for a node type of ELEMENT_NODE : Node.getTextContent()文档中 ,了解ELEMENT_NODE的节点类型:

concatenation of the textContent attribute value of every child node, excluding COMMENT_NODE and PROCESSING_INSTRUCTION_NODE nodes. 每个子节点(不包括COMMENT_NODE和PROCESSING_INSTRUCTION_NODE节点)的textContent属性值的串联。 This is the empty string if the node has no children. 如果节点没有子节点,则为空字符串。

Whereas for a text node, the return value of the method is just nodeValue , ie the text of the node. 而对于文本节点,该方法的返回值仅是nodeValue ,即节点的文本。

So yes - calling this on an element with a single child node which is a text node will give you the same results as calling it directly on that text node. 所以是的-在具有单个子节点(即文本节点)的元素上调用此方法, 获得与直接在该文本节点上调用它相同的结果。 But in other cases you'd get different results. 但是在其他情况下,您会得到不同的结果。 For example, if you had an element like this: 例如,如果您具有这样的元素:

<tag>1<break />2</tag>

there would be two child text nodes and one child element node, and the result would be "1 2" (or possibly "12"; I'm not sure how spacing works in this concatenation off-hand, but you can check). 将会有两个子文本节点和一个子元素节点,结果将为“ 1 2”(或可能为“ 12”;我不确定副手的级联间隔如何工作,但您可以检查)。

It's not a matter of a node "containing itself" - it's simply a matter of the definition of what this method does. 这与“包含自身”的节点无关,而仅与此方法的定义有关。

getTextContent() returns returns the text content of this node and its descendants . getTextContent()返回返回此节点及其后代的文本内容。

Statement A executed at tag1 returns the text node below ( 1 ) tag1执行的语句A返回下面的文本节点( 1

Statement B executed at the same place gets the child nodes of tag1 (a list with one text node), selects the first (only) text node and displays its text value. 在同一位置执行的语句B获取tag1的子节点(具有一个文本节点的列表),选择第一个(唯一的)文本节点并显示其文本值。

In this instance they are the same thing. 在这种情况下,它们是同一件事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM