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函数,子级和后代,没有结果。
如果有人可以告诉我如何在子节点中获取文本。
您不能在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中执行给定节点的所有文本后代的串联:
string-join(/TEXT/DESCR//text(), '')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句