简单 XML 读取元素命名空间属性

Simple XML read element namespace attribute

我有一个 XML,架构如下

$xml = 
'<NodeSet
    xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://opcfoundation.org/UA/2008/02/Types.xsd">
    <Node category="category" i:type="ObjectNode">
        <NodeId>
            <Identifier>i=86</Identifier>
        </NodeId>
    </Node>
</NodeSet>';

我需要从 Node 元素中提取 i:type 属性值。我试过像访问普通属性时那样访问它,但它似乎不能那样工作

下面是我如何访问类别属性,

$xml=simplexml_load_string($xml);
echo $xml->Node[0]['category']; //this prints 'category' as expected
echo $xml->Node[0]['i:type']; //prints nothing, how do i get the i:type attribute value ?

您需要使用命名空间访问属性,这可以使用 attributes() 方法来完成...

echo $xml->Node[0]->attributes("i",true)['type'];

使用 ("i",true) 表示使用 i 前缀而不是必须放置 URI。