如何使用XPath以XML格式获取所有后代文本内容

时间:2015-05-04 14:18:00

标签: php xml xpath

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函数,子函数和子函数,没有结果。

如果有人可以告诉我如何在子节点中获取文本。

2 个答案:

答案 0 :(得分:4)

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(), '')

答案 1 :(得分:0)

如果您无法更改输入XML,则可能会有效:

concat(/TEXT/DESCR,/TEXT/DESCR/PLUS)

string-join(/TEXT/DESCR/descendant-or-self::text())
相关问题