5

For one of my projects, I'm using the DOMDocument class to load and manipulate XML documents.

I'd need to retrieve every namespace used in the document; however, I can't find how I'd do that. The DOMDocument class has methods to get the namespace prefix of an URI or the URI of a namespace prefix, but I've seen nothing to actually enumerate registered namespaces.

The SimpleXML library has a getNamespaces() method for that. Is there an equivalent for DOMDocument?

4

1 回答 1

6

DOM 没有这样的功能 afaik。我已经简要地查看了 SimpleXml 的源代码,我认为它会迭代加载的 XML 并收集名称空间(我的 C 语言非常糟糕)。为此,最简单的解决方案是通过将 DOM dom 导入 SimpleXml 来获取命名空间。也许是这样的:

class DomUtils
{
    public static function getNamespaces($dom)
    {
        $sxe = simplexml_import_dom($dom);
        return $sxe->getNamespaces(); 
    }

    public static function getDocNamespaces($dom)
    {
        $sxe = simplexml_import_dom($dom);
        return $sxe->getDocNamespaces();
    }
}

您还可以尝试使用 XPath 获取所有名称空间。请参阅以下问题和答案:

于 2010-04-03T20:23:06.923 回答