Meaningless Drivel is fun!*
The moose likes XML and Related Technologies and the fly likes How to parse XML document with JDOM XPath Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "How to parse XML document with JDOM XPath" Watch "How to parse XML document with JDOM XPath" New topic
Author

How to parse XML document with JDOM XPath

Dhana Rengasamy
Greenhorn

Joined: Feb 26, 2010
Posts: 3
Hello expert,

Could you please help me to parse below xml document using JDom(or any Java API)XPath.

Thanks in Advance.

Dhana
Cisco


This is my xml file:

<key name="bookstore">
<key name="books">
<key name="science">
<key name="0001">
<entry name="auther">auther A</entry>
<entry name="price">$10</entry>
</key>
<key name="0002">
<entry name="auther">auther B</entry>
<entry name="price">$20</entry>
</key>
<key name="0003">
<entry name="auther">auther C</entry>
<entry name="price">$30</entry>
</key>
</key>
<key name="music">
<key name="0001">
<entry name="auther">auther A</entry>
<entry name="price">$10</entry>
</key>
<key name="0002">
<entry name="auther">auther B</entry>
<entry name="price">$20</entry>
</key>
<key name="0003">
<entry name="auther">auther C</entry>
<entry name="price">$30</entry>
</key>
</key>
</key>
</key>


Expected XPath / Result:

#1
bookstore/books/science/0001

result:

<key name="0001">
<entry name="auther">auther A</entry>
<entry name="price">$10</entry>
</key>

#2
bookstore/books/science/0001/auther

result:
auther A

#3
bookstore/books/science

result:
<key name="science">
<key name="0001">
<entry name="auther">auther A</entry>
<entry name="price">$10</entry>
</key>
<key name="0002">
<entry name="auther">auther B</entry>
<entry name="price">$20</entry>
</key>
<key name="0003">
<entry name="auther">auther C</entry>
<entry name="price">$30</entry>
</key>
</key>
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18716
    
    8

Here's an example of an XPath expression for your #1:

assuming that your context node is the document element.
Dhana Rengasamy
Greenhorn

Joined: Feb 26, 2010
Posts: 3
Paul Clapham wrote:Here's an example of an XPath expression for your #1:

assuming that your context node is the document element.


Thanks a lot Paul...

I got the solution for all my xpath which I mentioned.

The solution:

#1. *[@name='bookstore']/*[@name='books']/*[@name='science']/*[@name='0001']
#2. *[@name='bookstore']/*[@name='books']/*[@name='science']/*[@name='author']
#3. *[@name='bookstore']/*[@name='books']/*[@name='science']
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How to parse XML document with JDOM XPath