8

I have a node like this:

<meta name="og:description" content="Here's the content" />

I want to be able to select this element if the name is "description" whether it's in a namespace or not. I need to be able to select the meta tag if it's name is "og:description", "description", "blah:description", etc.

I've seen resources for xpath that show how to select within a namespace, but not irrespective of a namespace.

2
  • 7
    og:name="description" is namespace, but name="og:description" is just namespace-looking-like content, isn't it? Commented May 23, 2011 at 6:17
  • @abatishchev yes, you're right. I had the same reaction. Based on the accepted answer (which uses [ends-with(@name, 'description')]), apparently OP wanted to filter on "namespace-looking content". Based on the highest-voted answer with [local-name()="description"], you're right, other people want to filter on namespaced attribute name itself! Commented Apr 21, 2023 at 1:17

2 Answers 2

16

Use:

//meta[@*[local-name() = 'description']]

This selects all meta elements in the XML document that have an attribute with local-name "description".

By definition, the standard XPath function local-name() produces the name of the node from which the namespace prefix (if any) is stripped off.

If, on the other side you need to select a <meta> element the string value of whose name attribute is either "description" or any string that ends with ":description", use this XPath 1.0 expression:

//meta
   [@name = 'description' 
  or substring(@name, string-length(@name) - 11) = ':description']

Do note: Always avoid using the // pseudo operator if the structure of the XML document is statically known. Often using // causes slow execution.

Sign up to request clarification or add additional context in comments.

Comments

5

Using XPath 2 you could do:

 /meta[ends-with(@name, 'description')]

For XPath 1 we need:

 /meta['description' = substring(@name, string-length(@name) - string-length('description') + 1)]

1 Comment

This is obviously not a correct solution, as this selects only a top element meta. Also the meta top element will be selected even when the attribute name is Mydescription, yourdescription, ..., whateverdescription, Just noting these facts for the readers. Not downvoting!

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.