Travis
Travis

Reputation: 173

Java xpath selection

I'm having a little trouble getting values out of an XML document. The document looks like this:

<marketstat>  

<type id="35"> 
  <sell> 
    <median>6.00</median>  
  </sell> 
</type>  

<type id="34">    
  <sell> 
    <median>2.77</median> 
  </sell> 
</type>      

</marketstat> 

I need to get the median where type = x.

I've always had trouble figuring out xpath with Java and I can never find any good tutorials or references for this. If anyone could help me figure this out that would be great.

Upvotes: 3

Views: 395

Answers (4)

jaxvy
jaxvy

Reputation: 5090

You can do that easily with XQuery. To get the median of the type tag with where id is x you can write such a query;

for $var in doc('this_file.xml')//type
where $var/@id='x'
return data($var/sell/median)

Check out this tutorial for XQuery syntax:

Upvotes: 0

S&#233;bastienT
S&#233;bastienT

Reputation: 1

An other way to select your median node could be:

//type[@id='34']//median

You can find a lot of xpath query sample on http://www.zvon.org/xxl/XPathTutorial/General/examples.html

Upvotes: 0

cmaderthaner
cmaderthaner

Reputation: 447

For the XPATH side of the problem: this should do the trick

//*/type[@id='34']/*/median

When I am dealing with XPATH I usually use W3Schools as reference. And IBM DeveloperWorks has a tutorial for the Java XPath API

Upvotes: 2

Albert
Albert

Reputation: 2115

If your unfamiliar with Xpath you can install the FireXpath plugin into Firefox. It's a great way to verify your xpath expressions - and learn xPath.

Upvotes: 0

Related Questions