simplexml如何处理带前缀的元素


How does simplexml handle elements that are prefixed?

在应用程序中,simplexml一直在将rss提要转换为对象,并且元素非常容易引用。是以与对象中的无前缀元素($item->this)相同的方式引用的带前缀元素(例如<this:that>)。

我在php.net上的手册中没有找到任何信息。

不完全是。当您对表示名称空间XML的对象执行print_r()var_dump()时,您会注意到所有名称空间节点都丢失了。有几种方法可以获得具有名称空间的节点。一种方法是将registerXPathNamespace()与xpath()结合使用:

$xml = simplexml_load_file('some/namespaced/xml/file.xml');
$xml->registerXPathNamespace('prefix', 'http://Namespace/Uri/Here');
$xml->xpath('//prefix:node'); //get all <prefix:node> XML nodes.

另一种方法是使用children()获取子节点:

$xml = simplexml_load_file('some/namespaced/xml/file.xml');
$xml->children('prefix', true); //get all nodes with the 'prefix' prefix that are direct descendants of the root node.
$xml->someNode->children('blah', true); //get all nodes with the 'blah' prefix that are direct descendants of <someNode>

您要查找的是registerXPathNamespace()。您注册了每个名称空间,然后就可以像往常一样使用每个节点。