通过xpath和所有子元素获取父元素 [英] Get parent element through xpath and all child elements
问题描述
好吧,假设我有一些这样的 XML...
Ok so let’s say I have some XML like this…
<blaah1 name="whatever">
<gender name="male">
<example1 baseurl="male/86644/">
<x u="lol.png"/>
<x u="haha.png"/>
<x u="name.png"/>
</example1>
<example2 baseurl="male/27827/">
<x u="page.png"/>
<x u="examp.png"/>
<x u="bottom.png"/>
</example2>
</gender>
</blaah1>
我需要怎么做才能在每个孩子的父级 baseurl
末尾显示 u=""
内容?
What do I need to do to display the u=""
content on the end of the parent's baseurl
for each child?
推荐答案
据我所知,您不能使用单个 xpath 表达式来做到这一点,但您需要遍历结果.这种循环的一个例子:
As far as I know, you can not do that with a single xpath expression but you would need to loop over the result. An example of such a loop:
$base = '';
foreach($xp->query('//@baseurl|//*[@baseurl]/x/@u') as $element) {
$value = $element->value;
if (substr($value, -1,1) === '/') {
$base = $value;
} else {
echo $base, $value, "\n";
}
}
使用您的示例 XML 文档:
With your example XML document:
male/86644/lol.png
male/86644/haha.png
male/86644/name.png
male/27827/page.png
male/27827/examp.png
male/27827/bottom.png
此示例使用联合运算符 |
一次获取所有想要的节点.
This example is using the union operator |
to obtain all wanted nodes at once.
我最初是想在 xpath 中执行以下操作,但 AFAIK 是不可能的.但是 PHP 可以解决这个问题:在上下文中运行 Xpath 表达式到先前的 xpath 查询节点:
I was originally looking for doing the following within xpath but is not possible AFAIK. However PHP can take care of this: Run an Xpath expression in context to a previous xpath query nodes:
$array = array_map(function($context) use($xp) {
return $xp->evaluate('concat(../../@baseurl, .)', $context);
}, iterator_to_array($xp->query('//x/@u')));
给 $array
然后:
Array
(
[0] => male/86644/lol.png
[1] => male/86644/haha.png
[2] => male/86644/name.png
[3] => male/27827/page.png
[4] => male/27827/examp.png
[5] => male/27827/bottom.png
)
这可能更直接.
这篇关于通过xpath和所有子元素获取父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!