简体   繁体   English

Java按照它们在xml文档中出现的顺序检索具有不同标记名称的子节点

[英]Java Retrieve child nodes with different tag names in the order in which they appear in an xml document

I have an xml file which looked something like this... 我有一个看起来像这样的xml文件......

<RootElementTag>
   <ChildElementTag1 attribute1="value1" />
   <ChildElementTag1 attribute1="value2" />
   <ChildElementTag1 attribute1="value4" />
</RootElementTag>

I had to retrieve all the "ChildElementTag1" nodes and process them in the order in which they appear in the file. 我必须检索所有“ChildElementTag1”节点,并按照它们在文件中出现的顺序处理它们。 I used org.w3c.dom.Document.getElementsByTagName("ChildElementTag1"); 我使用了org.w3c.dom.Document.getElementsByTagName("ChildElementTag1"); which returned me a NodeList in the order in which it appears in the xml file. 它按照它在xml文件中出现的顺序返回给我一个NodeList。

Now the xml changed a bit and a new Child node with a different tag name "ChildElementTag2" is included. 现在xml发生了一些变化,并且包含了一个具有不同标记名称“ChildElementTag2”的新Child节点。

<RootElementTag>
   <ChildElementTag1 attribute1="value1" />
   <ChildElementTag1 attribute1="value2" />
   <ChildElementTag2 attribute2="value3" />
   <ChildElementTag1 attribute1="value4" />
   <ChildElementTag2 attribute2="value5" />
</RootElementTag>

Is there a way to get all the 5 Child Element Nodes in the above xml snippet in the order in which they appear. 有没有办法按照它们出现的顺序获取上述xml片段中的所有5个子元素节点。

Note:- I did see org.w3c.dom.Document.getElementById() method which would need me to introduce an "id" attribute to each child node and order them based on their "id" attribute value. 注意: - 我确实看到了org.w3c.dom.Document.getElementById()方法,它需要我为每个子节点引入一个“id”属性,并根据它们的“id”属性值对它们进行排序。 As of now I am not taking that approach hoping there is an easier way of doing this. 截至目前,我并没有采取这种方法,希望有一种更简单的方法。

Call getChildNodes() on the RootTagElement node. RootTagElement节点上调用getChildNodes()


The javadoc for this method does not mention that the NodeList returned in the order in which it appears in the document. 此方法的javadoc未提及NodeList按其在文档中出现的顺序返回。

I suspect you'll find they are in the same order as they appear in the document. 我怀疑你会发现它们与文档中出现的顺序相同。 OTOH, you might also look to methods listed just below the one to which I linked. OTOH,您也可以查看我链接的下方列出的方法。 Specifically getFirstChild() & getNextSibling() (which you would call on the first child, then repeatedly until null ). 特别是getFirstChild()getNextSibling() (您可以在第一个子getNextSibling()调用,然后重复调用直到null )。

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

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