Reputation: 6130
I'm using a library method for xpath evaluation (apache commons-text
's XmlStringLookup
) that sets the DocumentBuilderFactory
's namespace awareness to true
and I can't change that.
I need to query a pom.xml
file with this, that has a default namespace with no prefix:
<project xmlns="http://maven.apache.org/POM/4.0.0" ...>
<modelVersion>4.0.0</modelVersion>
...
I would want to be able to query just like:
/project/modelVersion
but because of the namespace awareness, the results come out empty. I know I can use something like :
//*[local-name()="project"] ...
but that's just cumbersome. The question is: is there any Xpath syntax to query namespaces without prefix? Something like:
/:project/:modelVersion
Upvotes: 3
Views: 368
Reputation: 111756
Within XPath, no, there is no alternative syntax that ignores namespaces, default or otherwise, other than testing against local-name()
(all versions) or *:NCName
(XPath 2.0 and later).
Within XPath, there also is no mechanism for binding namespace prefixes to namespaces. For a list of namespace prefix binding mechanisms that are available in various hosting languages and libraries, see How does XPath deal with XML namespaces?
Upvotes: 1
Reputation: 163645
If you move to XPath 3.1 (as delivered through Saxon 10.0), then
(a) /*:project
will retrieve an element with local name project, in any namespace (or none)
(b) /Q{http://maven.apache.org/POM/4.0.0}project
will retrieve an element with local name project in the specified namespace, with no need to declare namespace prefixes externally
(c) The Saxon API allows you to call XPathCompiler.declareNamespace("", "http://maven.apache.org/POM/4.0.0"), after which /project
selects an element in this namespace.
Upvotes: 2