How do I find all text nodes in an XML document with a namespace using XPath?

天大地大妈咪最大 提交于 2019-12-11 04:32:57

问题


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.


回答1:


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:")]



回答2:


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:".



来源:https://stackoverflow.com/questions/9382470/how-do-i-find-all-text-nodes-in-an-xml-document-with-a-namespace-using-xpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!