繁体   English   中英

XML xpath属性值

[英]XML xpath attribute value

如何获得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> 
foreach ($xml->Competency as $Comp) {
   echo $Comp['name']."\n";;
   }

结果

c
change management
coaching

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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM