Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select xml node by attribute name ignoring namespace of that attribute

Tags:

xml

xpath

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.

like image 730
wlmeurer Avatar asked May 23 '11 05:05

wlmeurer


2 Answers

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.

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

like image 105
Dimitre Novatchev Avatar answered Nov 17 '22 07:11

Dimitre Novatchev


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)]
like image 33
Richard Schneider Avatar answered Nov 17 '22 05:11

Richard Schneider