xml XPath:选择文本节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5033955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 14:33:16  来源:igfitidea点击:

XPath: select text node

xmlxpathselection

提问by kernel

Having the following XML:

具有以下 XML:

<node>Text1<subnode/>text2</node>

How do I select either the first or the second text node via XPath?

如何通过 XPath 选择第一个或第二个文本节点?

Something like this:

像这样的东西:

/node/text()[2]

of course doesn't work because it's the merged result of every text inside the node.

当然不起作用,因为它是节点内每个文本的合并结果。

回答by Dimitre Novatchev

Having the following XML:

<node>Text1<subnode/>text2</node> 

How do I select either the first or the second text node via XPath?

具有以下 XML:

<node>Text1<subnode/>text2</node> 

如何通过 XPath 选择第一个或第二个文本节点?

Use:

使用

/node/text()

This selects all text-node children of the top element (named "node") of the XML document.

这将选择 XML 文档顶部元素(名为“节点”)的所有文本节点子节点。

/node/text()[1]

This selects the first text-node child of the top element (named "node") of the XML document.

这将选择 XML 文档顶部元素(名为“节点”)的第一个文本节点子节点。

/node/text()[2]

This selects the second text-node child of the top element (named "node") of the XML document.

这将选择 XML 文档顶部元素(名为“节点”)的第二个文本节点子节点。

/node/text()[someInteger]

This selects the someInteger-th text-node child of the top element (named "node") of the XML document. It is equivalent to the following XPath expression:

这将选择 XML 文档顶部元素(名为“节点”)的 someInteger-th 文本节点子节点。它等效于以下 XPath 表达式:

/node/text()[position() = someInteger]

回答by kadalamittai

your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.

您的 xpath 应该可以工作。我已经在 MarkLogic 和 Zorba Xquery/Xpath 实现中测试了您和我的 xpath。

Both should work.

两者都应该工作。

/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2


/node/text()[1] - should return Text1
/node/text()[2] - should return text2