2012-09-12 57 views
1

比方說,我有這樣的XML:使用Xpath和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); 

返回空數組。現在我意識到我基本上是在挖掘一個孩子,然後回到父母身邊,但在我的情況下,這是我需要做的。我究竟做錯了什麼?我試圖獲得<Fieldsname>falsegoto</Fieldsname>父母兄弟姐妹的值爲<Tablename>

將於本鬥雞眼盯着....

回答

1

Fields沒有屬性Fieldsname它的一個子節點,也TablenameFields兄弟不是一個祖先。嘗試

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

非常感謝 - 總是一個簡單的錯誤。 – Jared

0

使用

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

這將選擇任何Tablename元素是具有一個孫子(其母公司爲FieldsFieldsname,其字符串值'truegoto'任何Table元素的孩子, (Table元素)是XML文檔的頂層元素的孫子。

請注意:用於

  1. 沒有反向軸。

  2. 因此,表達式更短,更簡單,更易於理解。