php SimpleXmlElement xpath按值替换节点。我可以按属性找到此节点吗?

时间:2018-05-23 09:35:16

标签: php xpath

我创建简单的xml:

<?xml version="1.0" encoding="UTF-8"?>
<s>
  <s n="level1">
    <c n="level2">
        <s>
            <s n="level4">
                <a n="name1" />
                <a n="name2" />
                <a n="name3">20160826</a>
                <a n="name4">01</a>
                <a n="name5">01</a>
            </s>
            <a n="name6">1</a>
            <a n="name7" />
            <a n="name8" />
            <a n="name9">6</a>
        </s>
    </c>
  </s>
</s>

然后将此文件加载为:     

$xmlObject = simplexml_load_file($filepath); 
$aCollection = $xmlObject->xpath('/s/s[@n="level1"]/c[@n="level2"]/s');
print_r($aCollection);

结果我有下一个数据:

Array(
    [0] => SimpleXMLElement Object (
            [s] => SimpleXMLElement Object 
                    [@attributes] => Array (
                            [n] => level4
                        )
                    [a] => Array (
                            [0] => SimpleXMLElement Object (
                                    [@attributes] => Array (
                                            [n] => name1
                                        )
                                )
                            [1] => SimpleXMLElement Object (
                                    [@attributes] => Array (
                                            [n] => name2
                                        )
                                )
                            [2] => 20160826
                            [3] => 01
                            [4] => 01
                        )
                )
            [a] => Array (
                    [0] => 1
                    [1] => SimpleXMLElement Object (
                            [@attributes] => Array (
                                    [n] => name7
                                )
                        )
                    [2] => SimpleXMLElement Object (
                            [@attributes] => Array (
                                    [n] => name8
                                )
                        )
                    [3] => 6
                )
        )
)

具有值的所有节点都将消失。 结果中只有空节点。

我想浏览每个$ aCollection(结果数组)元素,并按每个元素中的属性值查找节点(如$element->xpath('/a[@n="name6"]'))。

但现在没有属性值为“name6”和“name9”的节点。

1 个答案:

答案 0 :(得分:1)

Don't use print_r to inspect SimpleXML objects。一切都还在,你只需要访问它。试试这个:

foreach ($xmlObject->xpath('/s/s[@n="level1"]/c[@n="level2"]/s') as $element) 
{
    if ($element->xpath('./a[@n="name6"]')) {
        // Do something with $element->xpath('./a[@n="name6"]')[0]
    }
}

请参阅https://eval.in/1008597