使用Xpath和PHP获取XML父/祖先的值


Get value of XML parent/ancestor using Xpath and PHP?

假设我有这个XML:

<Routes>
  <Route ref="timeconditions">
   <Table>
     <Tablename>timeconditions</Tablename>
     <Fields>
       <Fieldsname>truegoto</Fieldsname>
     </Fields>
   </Table>
  </Route>
</Routes>

PHP:

$doc    = new SimpleXMLElement('routingConfig.xml', null, true);
$foo = $doc->xpath('/Routes/Route[@ref="timeconditions"]/Table/Fields[@Fieldsname="truegoto"]/ancestor::Tablename');
print_r($foo);

返回空白数组。现在我意识到,我基本上是在挖掘一个孩子,然后支持他的父母,但在我的背景下,这就是我需要做的。我做错了什么?我正在尝试获取名为<Tablename><Fieldsname>falsegoto</Fieldsname>父母兄弟姐妹值。

瞪大眼睛看着这个。。。。

Fields没有属性Fieldsname,它是子节点,而且TablenameFields的兄弟,而不是祖先。尝试

$foo = $doc->xpath('/Routes/Route[@ref="timeconditions"]/Table/Fields[Fieldsname="truegoto"]/preceding-sibling::Tablename');

使用

/*/*/Table[Fields/Fieldsname = 'truegoto']/Tablename

这选择了作为具有字符串值为'truegoto'的孙子(其父级为FieldsFieldsname的任何Table元素的子级的任意Tablename元素,并且(Table元素)是XML文档的顶部元素的孙子。

注意

  1. 不使用反向轴。

  2. 正因为如此,表达式更短、更简单、更容易理解。