繁体   English   中英

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

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

在这里,我在下面提到了我们通常在Dom节点上进行工作的方式。 我想找到一种方法来按名称获取特定的节点调用,而无需在对代码进行注释时遍历整个列表。

        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...
            }

        }

注意:我知道可以使用XPath完成。 但是我在DOM中寻找一种方法,这里NodeList表示org.w3c.dom.NodeList,而Node表示org.w3c.dom.Node。 (在“从节点列表中按名称获取节点”中的回答提供了XPath解决方案)

正如MadProgrammer所说,如果您传递节点,则可以使用XPath轻松完成。 因此,在我的情况下,我通过了派生父节点/文档来派生NodeList,如下所示。

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

得到一个字符串:

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

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

暂无
暂无

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

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