XML xpath属性值

时间:2015-06-23 12:34:51

标签: php xml simplexml

如何获取xml xpath输出的属性值?

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [name] => c
                )

        )

    [1] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [name] => change management
                )

        )

    [2] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [name] => coaching
                )
        )
)

这是我的对象,我需要提取值" c","更改管理"和"教练"

这就是我的xml的样子

<Competency name="c">
</Competency>
<Competency name="change management">
</Competency>
<Competency name="coaching">
</Competency> 

2 个答案:

答案 0 :(得分:0)

foreach ($xml->Competency as $Comp) {
   echo $Comp['name']."\n";;
   }

结果

c
change management
coaching

答案 1 :(得分:0)

SimpleXmlElement::xpath()始终返回SimpleXMLElement个对象的数组。即使表达式返回属性节点列表。在这种情况下,属性节点将转换为SimpleXMLElement个实例。如果将它们转换为字符串,您将获得属性值:

$element = new SimpleXMLElement($xml);
foreach ($element->xpath('//Competency/@name') as $child) {
  var_dump(get_class($child), (string)$child);
}

输出:

string(16) "SimpleXMLElement"
string(1) "c"
string(16) "SimpleXMLElement"
string(17) "change management"
string(16) "SimpleXMLElement"
string(8) "coaching"

如果这很神奇,你需要使用DOM。它更具可预测性和明确性:

$document = new DOMDocument($xml);
$document->loadXml($xml);
$xpath = new DOMXPath($document);

foreach ($xpath->evaluate('//Competency/@name') as $attribute) {
  var_dump(get_class($attribute), $attribute->value);
}

string(7) "DOMAttr"
string(1) "c"
string(7) "DOMAttr"
string(17) "change management"
string(7) "DOMAttr"
string(8) "coaching"