Craig Walker
Craig Walker

Reputation: 51787

Select Element in a Namespace with XPath

I want to select the topmost element in a document that has a given namespace (prefix).

More specifically: I have XML documents that either start with /html/body (in the XHTML namespace) or with one of several elements in a particular namespace. I effectively want to strip out /html/body and just return the body contents OR the entire root namespaced element.

Upvotes: 12

Views: 13057

Answers (2)

Jim Burger
Jim Burger

Reputation: 4547

In XPath 2.0 and XQuery 1.0 you can test against the namespace prefix using the in-scope-prefixes() function in a predicate. e.g.

//*[in-scope-prefixes(.)='html']

If you cant use v2, in XPath 1.0 you can use the namespace-uri() function to test against the namespace itself. e.g.

//*[namespace-uri()='http://www.w3c.org/1999/xhtml']

Upvotes: 10

Craig Walker
Craig Walker

Reputation: 51787

The XPath expression that I want is:

/html:html/html:body/node()|/foo:*

Where the "html" prefix is mapped to the XHTML namespace, and the "foo" prefix is mapped to my target namespace.

Upvotes: 3

Related Questions