2014-01-06 41 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";