如何使用XPath检索子子节点?

时间:2015-01-04 14:51:59

标签: php xml xpath

我正在测试XML结构:

<Articles>


...


   <Article ID="333">

     <author>Paul</author>

     <title>i hate xpath </title>

        <child1>bla</child1>

       <child2>blabla
          <subchild>
             <subsubchild DEEP = "Attribute"></subsubchild>     //this is my nightmare
          </subchild>
       </child2>

       <child3>testing</child3>

   </Article> 
...

</Articles>

XPath表达式将获取并更新subsubchild attrib值?我主要关心的是获取和更新任何节点的子值,无论多么深刻或表面位置,如果父ID(在这种情况下为333)是已知的。

目前我使用过:

$query= "//*[@ID=333]//*node()[@DEEP and @DEEP = "Attribute"]";
$outcome = $xml->xpath($query);
    echo isset($outcome[0][0]) ? "found" : "unavailable";

以及其他一些相关的表达方式,它们都会让我对Invalid表达式报告的努力感到沮丧。

function XMLChangeAttribValue($ParentID, $attirbName, $attribValue, $NewValue){
        
            $xml    //Never mind, i've create this sucessfully 

 
            $query = "//*[@ID=$ParentID]//*[@$attirbName = $attribValue]";
                    

            $outcome = $xml->xpath($query);
            echo isset($outcome[0][0]) ? "found" : "unavailable";
}

1 个答案:

答案 0 :(得分:2)

在这种情况下,选择您要定位的subsubchild的XPath是:

$query = "//*[@ID=333]//*[@DEEP = 'Attribute']";

要选择属性本身,您可以使用:

$query = "//*[@ID=333]//*/@DEEP[. = 'Attribute']";

请注意,我在字符串中使用了单引号,因为除非你将它们转义,否则不能在双引号字符串中使用双引号。

还应注意,在一个clump中使用*node() all在XPath表达式中无效。