这是我的 XML(片段):
<?xml version="1.0" encoding="utf-8"?>
<test>
<body label_position="left">
<page number="1">
<itemset name="">
<item name="" id="1" />
<item name="" id="2" label_position="right" />
</itemset>
</page>
</body>
</test>
我想完成的事情:
是否<item id="1">
有一个label_position
属性集?
(1) 如果是,则返回。
(2) 如果不是,检查该节点的父节点的属性。
(3) 如果parent有该属性,则返回。
(4) 如果不是,转步骤(2)。 <body>
是要检查的“最旧”节点。
我尝试过的:
我正在使用 simplexml
和 xpath
, 我试着选择 <item>
及其所有祖先,然后向上遍历树并在第一次出现 label_position
时停止.
$xml->xpath("//item[@id='1']::ancestors-or-self/@label_position");
产生了 invalid expression
.
(1) 如何让这个表达式起作用?
(2) 这可以用“xpath-only”完成吗 - 无需遍历树并进行搜索?
编辑:多亏了 choroba 和 dirkk,我才能够把它放在一起:
$test = (string)array_reverse($xml->xpath("//item[@id='2']/ancestor-or-self::*/@label_position"))[0];
解释:如果两个<item>
和 <body>
具有属性,xpath
将返回一个包含两个值的数组,<body>
第一个。在这种情况下,我想获得 <item>
首先,这就是为什么 array_reverse()
.
最佳答案
您应该更加注意 XPath 语法。你的正确表达形式是
//item[@id='1']/ancestor-or-self::*/@label_position
不能在谓词后使用::
,必须在轴后指定::
。
关于xml - 遍历 XML 树获取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17528364/