2014-01-06 39 views
1

我有這樣的XML:的SimpleXML的XPath檢索屬性,而不是文本值

<root> 
    <parent> 
     <child id="childAtt"> 
      <subChild id="subAtt">Value to retrieve</subChild> 
     </child> 
    </parent> 
</root> 

目前我試圖用這個XPath來檢索subChild的文本值:

$total = $xml->xpath("/*//child[@id='childAtt']/subChild[@id='subAtt']"); 

然而,這將返回subChild屬性值而不是節點的文本值。

我想知道如何檢索subChild的文本值,其編號爲subAtt

回答

1

你只需要訪問的第一個元素,並強制轉換它作爲一個字符串:

$total = (string) $xml->xpath("/*//child[@id='childAtt']/subChild")[0]; 
var_dump($total); 

輸出:

string(17) "Value to retrieve" 
0

您也可以嘗試將文字直接與您的XPath查詢提取:

$total = (string) $xml->xpath("/*//child[@id='childAtt']/subChild/text()") 
0

您的查詢確實 select the eleme NT。只是爲了擴大@阿邁勒的回答,您查詢的結果是,看起來這一切結果的數組:

array(1) { 
    [0] => 
    class SimpleXMLElement#2 (2) { 
    public [email protected] => 
    array(1) { 
     'id' => 
     string(6) "subAtt" 
    } 
     string(17) "Value to retrieve" 
    } 
} 

在口頭上:第一個元素是SimpleXMLElement實例,它的字符串值所需的文本。

一個完整的例子:

$string = <<<XML 
<root> 
    <parent> 
     <child id="childAtt"> 
      <subChild id="subAtt">Value to retrieve</subChild> 
     </child> 
    </parent> 
</root> 
XML; 

$xml = new SimpleXMLElement($string); 
$result = $xml->xpath("/*//child[@id='childAtt']/subChild[@id='subAtt']"); 

var_dump($result); 
print (string) $result[0] . "\n";