【问题标题】:How to get a particular DOM node calling by name on the NodeList (Not in XPath) in javajava - 如何在Java中的NodeList(不在XPath中)上按名称调用特定的DOM节点
【发布时间】:2014-05-15 21:03:13
【问题描述】:

这里我在下面提到了我们通常在 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。 (Get Node by Name from Nodelist中的回答提供了XPath解决方案)

【问题讨论】:

  • XPath 与 DOM 配合得非常好,对于 exampleexample
  • 是吗?你的意思是我可以将 DOM NodeList 传递给 XPath 并获得一个 DOM 节点?
  • 好的,抱歉,您正在尝试传递NodeList,可能不好...
  • 是的。没关系。并感谢您的资源。

标签: java xml dom


【解决方案1】:

正如 MadProgrammer 所说,如果您传递的是 Node.js,则可以使用 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/

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2013-02-06
    • 2018-08-09
    • 2021-12-23
    • 1970-01-01
    • 2015-08-22
    • 2012-03-01
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多