1

I know I can select nodes by attribute name using

//*[@attribute]

But how do I do it if my attribute is a namespace like bar:resource?

For example:

<foo:creator bar:resource="https://example/john">john</foo:creator>

1 Answer 1

1

Pretty much same stuff:

//*[@bar:resource]

This XPath selects all nodes which have @bar:resource attribute. To use this, you need to pass namespace uri and namespace prefix (bar) into your XML/XPath engine/processor.

Alternatively you can use pure XPath (although I don't recommend this):

//*[@*[local-name() = 'resource' and namespace-uri() = 'bar_namespace_uri']]
Sign up to request clarification or add additional context in comments.

3 Comments

Can you elaborate on why you don't recommend doing a //*[@*[local-name() = 'resource']] select?
@vinhboy, first of all, this XPath //*[@*[local-name() = 'resource']] doesn't check namespace of the attribute, i.e. resource="" and bar:resource="" both have local-name resource.
@vinhboy, which means, to make it consistent with //*[@bar:resource] you also need to check namespace of the attribute, e.g.: //*[@*[local-name() = 'resource' and namespace-uri() = 'bar_namespace_uri']]. I don't recommend this approach in terms of maintenance and flexibility: imagine you have many queries which all need to check namespace. This means in every query you need to specify namespace uri, which leads to code duplication, potential errors, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.