Jared
Jared

Reputation: 1793

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

Let's say I have this 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);

Returns blank array. Now I realize I'm basically digging into a child then backing up to it's parent, but in my context that is what I need to do. What am I doing wrong? I'm trying to get <Fieldsname>falsegoto</Fieldsname> parents sibling value called <Tablename>.

Going crosseyed staring at this....

Upvotes: 1

Views: 1243

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243469

Use:

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

This selects any Tablename element that is a child of any Table element that has a grandchild (whose parent is Fields) Fieldsname whose string value is 'truegoto', and that (the Table element) is a grandchild of the top element of the XML document.

Do note:

  1. No reverse axes are used.

  2. Because of this, the expression is shorter, simpler and easier to understand.

Upvotes: 0

Musa
Musa

Reputation: 97672

Fields has no attribute Fieldsname its a child node, also Tablename is a sibling of Fields not an ancestor. Try

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

Upvotes: 1

Related Questions