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

StackOverflow https://stackoverflow.com/questions/23670548

  •  23-07-2023
  •  | 
  •  

Question

Here I have mentioned in below the way that we are normally working on the Dom nodes. 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. But I'm looking for a way in DOM Here NodeList means org.w3c.dom.NodeList and Node means org.w3c.dom.Node. (Answer in Get Node by Name from Nodelist provides the XPath solution)

Était-ce utile?

La solution

As MadProgrammer said, This can be easily done with XPath if you are passing a Node. So, in my case I passed the Parent Node / Document that I took to derive the NodeList as follows.

 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/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top