Suppose I have this XML:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:foo="http://www.foo.com">
<foo:one>Alpha</foo:one>
<two foo:Dog="Yorkie">Bravo</two>
<three>foo:Delta</three>
</root>
If I want to use XPath to find all elements that are in the "http://www.foo.com" namespace (such as the element "one"), I can use this:
//*[namespace-uri()='http://www.foo.com']
If I want to find all elements that have an attribute in that namespace (such as the element "two"), I can use this:
//@*[namespace-uri()='http://www.foo.com']
If I want to find all elements that have a text node in that namespace (such as the element "three"), what XPath can I use?
XPath 1 or 2 allowed. Thanks.
There is no such thing as a namespace on a text node; your three
node just contains the text foo:Delta
, which has no special meaning in XML. You can find nodes holding text starting with foo:
using starts-with
:
//*[starts-with(., "foo:")]
If I want to find all elements that have a text node in that namespace
(such as the element "three"), what XPath can I use?
Only nodes that have a name can be in a namespace.
Thus: text-nodes, comments and document nodes do not have a (belong to) namespace.
The name of a PI also doesn't belong to any namespace.
Therefore, there is nothing like "a text node in that namespace"...
In this particular case you can select the wanted elements using this XPath expression:
//*[text()[starts-with(., 'foo:')]]
this selects any element in the XML document that has at least one text-node child whose string-value starts with the string "foo:"
.