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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
wlmeurer
  • 133
  • 1
  • 5
  • 7
    `og:name="description"` is namespace, but `name="og:description"` is just namespace-looking-like content, isn't it? – abatishchev May 23 '11 at 06: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! – Nate Anderson Apr 21 '23 at 01:17

2 Answers2

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.

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
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)]
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73
  • 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! – Dimitre Novatchev Aug 15 '22 at 03:23