Reputation: 6202
I have the XML below and want to select the value of the name
attribute of element category
.
I looked here and here and here.
I actually want xpath 1.0, so I tried:
/result/products/product/*:[local-name() = 'categories']/*:[local-name() = 'category']/@name
Since that didn't work I also just attempted xpath 2.0:
/result/products/product/*:categories/*:category/@name
If I remove the namespace prefixes from the source document, the selector /result/products/product/categories/category/@name
returns the correct value.
So, how can I ignore namespaces in my selectors?
<result version="3.0"
xmlns="urn:com:tradedoubler:pf:model:xml:output"
xmlns:ns2="urn:com:tradedoubler:pf:model:xml:common">
<products>
<product>
<ns2:name>MY name</ns2:name>
<ns2:productImage>https://www.google.com/assets/1400x1960/1519833875/18053428-6dv7qPqW.jpg</ns2:productImage>
<ns2:categories>
<ns2:category name="Living>Curtains>Curtains"></ns2:category>
</ns2:categories>
</product>
</products>
</result>
Upvotes: 1
Views: 1150
Reputation: 824
[code]/*:result/*:products/*:product/*:categories/*:category/@name[/code]
Upvotes: -1
Reputation: 29052
Your XPath expression is wrong: you have superfluous :
in your expression and you also need to take the default namespace xmlns="urn:com:tradedoubler:pf:model:xml:output"
into account which affects all children of the <result>
element.
So use the following expression:
/*[local-name() = 'result']/*[local-name() = 'products']/*[local-name() = 'product']/*[local-name() = 'categories']/*[local-name() = 'category']/@name
Upvotes: 2
Reputation: 23012
In your XML, all elements which don’t have a namespace prefix are in the default namespace, which is xmlns="urn:com:tradedoubler:pf:model:xml:output".
So you need to fix your xpath to introduce this namespace. A good practice is to use an extra namespace prefix for that, for instance:
xmlns:o="urn:com:tradedoubler:pf:model:xml:output"
Your xpath becomes:
/o:result/o:products/o:product/*:[local-name() = 'categories']/*:[local-name() = 'category']/@name
You can also use the ns2 namespace:
/o:result/o:products/o:product/ns2:categories/ns2:category/@name
Upvotes: 0