XML 文件
<TEXT>
<DESCR>
Here is the first part...
<PLUS>The second</PLUS>
And the third
</DESCR>
</TEXT>
我期望得到的:
Here is the first part...The secondAnd the third
我实际得到的:
Here is the first part...And the third.
我尝试了 descendant-or-self::*
xPath 函数、child 和 descendant,没有结果。
如果有人能告诉我如何也获取子节点中的文本。
最佳答案
XPath 1.0
您不能在 XPath 1.0 中执行给定节点的所有文本后代的连接。您可以在 XPath 中选择节点,
/TEXT/DESCR//text()
但随后您必须使用宿主语言执行串联。
在 PHP 中:
$xml = '<TEXT>
<DESCR>
Here is the first part...
<PLUS>The second</PLUS>
And the third
</DESCR>
</TEXT>';
$dom = new DOMDocument();
$dom->loadXML($xml);
$x= new DOMXpath($dom);
foreach($x->query("/TEXT/DESCR//text()") as $node) echo trim($node->textContent);
会输出你请求的结果:
Here is the first part...The secondAnd the third
[或者,如果您没有其他理由遍历文本节点,请将上面的 foreach
循环替换为:]
$xml = '<TEXT>
<DESCR>
Here is the first part...
<PLUS>The second</PLUS>
And the third
</DESCR>
</TEXT>';
$dom = new DOMDocument();
$dom->loadXML($xml);
$x= new DOMXpath($dom);
echo str_replace(PHP_EOL, '', $x->evaluate('normalize-space(/TEXT/DESCR)'));
产生:
Here is the first part... The second And the third
XPath 2.0
您可以在 XPath 2.0 中执行给定节点的所有文本后代的串联:
string-join(/TEXT/DESCR//text(), '')
关于php - 如何使用 XPath 获取 XML 中的所有后代文本内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30032450/