GRoutar
GRoutar

Reputation: 1425

How to retrieve name from XPATH

I'm trying to make a XPATH which returns the name of the products whose count is higher than 5.

This is the XML:

<?xml version ="1.0" encoding ="UTF -8"?>
<list>
   <product>
      <name>A</name>
      <parts>
         <part count="3">X3</part>
         <part count="1">Y2</part>
         <part count="2">Z6</part >
      </parts>
   </product>
   <product>
      <name>B</name>
      <parts>
         <part count="1">G3</part>
         <part count="2">Y6</part>
      </parts>
   </product>
   <product>
      <name>C</name>
      <parts>
         <part count="6">K9</part >
         <part count="3">Y6</part>
      </parts>
   </product>
</list>

My attempt was:

//name/following-sibling::parts/part[@count>5]

More readable version
/list/product/parts/part[@count>5] 

The XPATH I made returns <part count="6">K9</part > which is partially correct, but it doesn't return the name of the product. At this point I'm not even sure if I'm supposed to return the actual name (C in this case) and if it's even possible to do so or if my method is correct. Any input would be welcome.

Upvotes: 1

Views: 51

Answers (2)

Nuno
Nuno

Reputation: 496

You can achieve that using the following xpath

/list/product/parts/part[@count>5]/../../name

Hope it helps.

Upvotes: 1

Tomalak
Tomalak

Reputation: 338108

How about

//product[parts/part/@count > 5]/name

or

//part[@count > 5]/ancestor::product/name

or

//name[../parts/part/@count > 5]

There are many ways to skin a cat, as they say.

Upvotes: 3

Related Questions