php - 如何使用 XPath 获取 XML 中的所有后代文本内容

标签 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 函数、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/

相关文章:

php - 数据库查询字符串 URL

xml - 如何使用go检查XML文件中是否存在标签?

c# - 在 XML 文件中有效地存储图像

python - Scrapy xpath错误: 'Selector' object has no attribute '_default_type'

xslt - 用div包裹两个值大于0的节点

php - 根据邮政编码自动填写国家和城市,反之

php - 如何将另一个 Laravel 验证规则与 'required_without_all' 结合起来

sql - 从 SQL 查询创建 XML 文档

xslt - XSL:如何最好地将节点存储在变量中,然后在以后的xpath表达式中使用它?

php - 插入仅执行第一行