XPATH获取当前节点的属性

时间:2014-06-27 20:18:08

标签: php xpath

无法在PHP中获取当前节点的属性并根据该属性创建条件...

示例XML

<div class='parent'>
    <div class='title'>A Title</div>
    <div class='child'>some text</div>
    <div class='child'>some text</div>
    <div class='title'>A Title</div>
    <div class='child'>some text</div>
    <div class='child'>some text</div>
</div>

我想要做的是在PHP中遍历XML并根据元素/节点的类做不同的事情

例如

$doc->loadHTML($xml_string);
$xpath = new DOMXpath($doc);
$nodeLIST = $xpath->query("//div[@class='parent']/div");
foreach ($nodeLIST as $node) {
    if (CURRENT DIV NODE ATTRIBUTE EQUALS TITLE) {
        SET $TITLE VARIABLE TO THE TEXT() OF THE CURRENT NODE
    }
    ELSEIF(CURRENT DIV NODE ATTRIBUTE EQUALS CHILD){
        SET $CHILD VARIABLE TO THE TEXT() OF THE CURRENT NODE
    }
}

我尝试了以下各种各样的事情......

if ($xpath->query("./[@class='title']/text()",$node)->length > 0) { }

但我不断得到的是PHP错误,说我的XPATH语法无效。任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:4)

您可以使用getAttribute()方法实现此目的。例如:

foreach($nodeLIST as $node) {
    $attribute = $node->getAttribute('class');
    if($attribute == 'title') {
        // do something
    } elseif ($attribute == 'child') {
        // do something
    }
}

答案 1 :(得分:1)

$node->getAttribute('class')为您提供属性值$node->textContent节点的字符串内容。我不会深入XPath读出字符串值。

答案 2 :(得分:0)

您可以过滤不同节点列表中的“标题”和“子”集:

$titles   = $xpath->query("//div[@class='parent']/div[@class='title']");
$children = $xpath->query("//div[@class='parent']/div[@class='child']");

然后单独处理它们:

foreach ($titles as $title) {
   echo $title->textContent."\n";
}

foreach ($children as $child) {
   echo $child->textContent."\n";
}

请参阅:http://codepad.viper-7.com/x4LA50