简体   繁体   English

如何在Java中的NodeList上按名称获取特定的DOM节点(不在XPath中)

[英]How to get a particular DOM node calling by name on the NodeList (Not in XPath) in java

Here I have mentioned in below the way that we are normally working on the Dom nodes. 在这里,我在下面提到了我们通常在Dom节点上进行工作的方式。 I want to find a way to get particular node calling by name without iterating over the entire list as I commented on the code. 我想找到一种方法来按名称获取特定的节点调用,而无需在对代码进行注释时遍历整个列表。

        NodeList                nodeList                = _myDoc.getElementsByTagName("Parent");

        // I want to get child2 node here calling by name without iterating over entire list

        for (int i = 0; i < nodeList.getLength(); i++) {

            Node node = nodeList.item(i);               

            if (node.getLocalName() != null) {

                if (node.getLocalName().equals("child1")) {

                    // get node as child1

                }else if (node.getLocalName().equals("child2")) {

                    // get node as child2

                }etc...
            }

        }

Note : I know that this can be done with XPath. 注意:我知道可以使用XPath完成。 But I'm looking for a way in DOM Here NodeList means org.w3c.dom.NodeList and Node means org.w3c.dom.Node. 但是我在DOM中寻找一种方法,这里NodeList表示org.w3c.dom.NodeList,而Node表示org.w3c.dom.Node。 (Answer in Get Node by Name from Nodelist provides the XPath solution) (在“从节点列表中按名称获取节点”中的回答提供了XPath解决方案)

As MadProgrammer said, This can be easily done with XPath if you are passing a Node. 正如MadProgrammer所说,如果您传递节点,则可以使用XPath轻松完成。 So, in my case I passed the Parent Node / Document that I took to derive the NodeList as follows. 因此,在我的情况下,我通过了派生父节点/文档来派生NodeList,如下所示。

 Node node = (Node) XPathFactory.newInstance().newXPath().compile(stringXPathExpression).evaluate(nodeOrDocument, XPathConstants.NODE);

To get a String : 得到一个字符串:

String  currencyCodeInTotal = XPathFactory.newInstance().newXPath().compile(stringXPathExpression).evaluate(node);

Reference : http://viralpatel.net/blogs/java-xml-xpath-tutorial-parse-xml/ 参考: http : //viralpatel.net/blogs/java-xml-xpath-tutorial-parse-xml/

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

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