PHP SimpleXML Xpath 仅相对于当前节点的路径

huangapple go评论63阅读模式
英文:

PHP SimpleXML Xpath Relative to Current Node Only

问题

我正在尝试运行一个简单的PHP SimpleXML命令,使用xpath。但是,我的//w:pStyle XPath选择了整个文档中的所有节点,而不是相对于正在循环的//w:p节点。**注意:**我希望保持两个xpaths的循环分开。我不想将它们放在一个xpath下,即如果段落中存在样式节点,则首先循环段落节点,然后仅循环该段落中的样式节点。解决方法是什么?

英文:

I am trying to run a simple PHP SimpleXML command using xpath. But, my //w:pStyle Xpath is getting all nodes in the entire document and not the ones relative to the node //w:p thats being looped. Note: I want to keep the loop for both xpaths separate. I do not want to have both under one xpath i.e. loop through the paragraph nodes and then loop the styles nodes only in that paragraph if they exist.

 foreach($file->xpath('//w:p') as $p){
  echo 'Paragraph';
  $styles=$p->xpath('//w:pStyle');
  foreach($styles as $style){echo 'Style';}
 }

The xpath //w:pStyle selects all the w:pStyle nodes. I would like instead for it to select the ones that are relative to the paragraph node. What is the solution here?

答案1

得分: 1

你的错误在于,在表达式前面加上 // 来选择整个文档中的元素。你应该使用 .// 替代,像这样:

$styles=$p->xpath('.//w:pStyle');

这样会选择 w:p 元素的所有 w:pStyle 后代。

如果你只想选择 w:p 的直接子元素,可以使用:

$styles=$p->xpath('w:pStyle');

因为 w:pStylew:pPr 的子元素,而 w:pPrw:p 的子元素,所以你可以使用:

$styles=$p->xpath('w:pPr/w:pStyle');
英文:

Your mistake is, that you are selecting elements from the whole document by prefixing the expression with //. You should prefix it with .// instead, like this

$styles=$p->xpath('.//w:pStyle');

which will select all w:pStyle descendants of the w:p element.
If you only want direct children of w:p, use

$styles=$p->xpath('w:pStyle');

since w:pStyle is a child of w:pPr which is a child of w:p, you could use

$styles=$p->xpath('w:pPr/w:pStyle');

huangapple
  • 本文由 发表于 2023年7月3日 10:37:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601556.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定