Anand B
Anand B

Reputation: 3085

Getting Xpath node values in nested XML

My xml structure is like,

<items>
<item>
    <brand>
        <id> 3 </id>
     </brand>
    <product>
        <productType>Type 1</productType>
    </product>
</item>
<item>
    <brand>
        <id> 4 </id>
     </brand>
    <product>
        <productType>Type 2</productType>
    </product>
</item>
</items>

I need to get the product type value if the user provides the brand id. For eg, if the user enters brand id 3, then I need to return the product type Type 1

I tried with Xpath expression

 /items/item/brand[id = 3]/product/productType

But it does not work. What will be the correct xpath expression.

Upvotes: 1

Views: 2445

Answers (1)

Rolando Isidoro
Rolando Isidoro

Reputation: 5114

You have a simple nesting problem since brand is a sibling to product and not an anscestor like your XPath query implies.

Simply change to:

/items/item[brand/id = 3]/product/productType

Result:

Element='<productType>Type 1</productType>'

Try it at http://www.freeformatter.com/xpath-tester.html.

Upvotes: 3

Related Questions