Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a node from xml not knowing its level in Java

Tags:

java

dom

xml

We have tree structure like this:

<Tree>
   <child1>
         <child2>
         <child2>
   </child1>
</Tree>

Here the child2 can be at any level. Is there any way we can access child2 without knowing the hierarchy?

Thanks for all answer..is there any way in Castor?as we are using Castor for marshalling and unmarshilling

Here is a similar type of question: How to get a node from xml not knowing its level in flex?

like image 586
Vish Avatar asked Aug 05 '26 07:08

Vish


2 Answers

Using XPath, you could do it something like this:

XPath xpath = XPathFactory.newInstance().newXPath();
NodeList child2Nodes= (NodeList) xpath.evaluate("//child2", doc, 
    XPathConstants.NODESET);

Where doc is your org.w3c.dom.Document class.

like image 145
Jeff Olson Avatar answered Aug 07 '26 19:08

Jeff Olson


Use XPath to get the nodes.
//child2 - to get the list of all "child2" elements

like image 33
alexblum Avatar answered Aug 07 '26 20:08

alexblum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!