枚举PHP DOMDocument对象的注册名称空间 [英] Enumerate registered namespaces of a PHP DOMDocument object
问题描述
对于我的一个项目,我正在使用 DOMDocument
类加载和操作XML文档。
For one of my projects, I'm using the DOMDocument
class to load and manipulate XML documents.
我需要检索文档中使用的每个名称空间;但是,我找不到我该怎么做。 DOMDocument
类具有获取URI的名称空间前缀或名称空间前缀的URI的方法,但是我没有看到任何枚举注册的名称空间的方法。
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.
SimpleXML
库为此提供了 getNamespaces()
方法。 DOMDocument
是否有等效项?
The SimpleXML
library has a getNamespaces()
method for that. Is there an equivalent for DOMDocument
?
推荐答案
DOM没有这样的功能功能afaik。我简要地看过SimpleXml的源代码,我认为它会迭代加载的XML并收集名称空间(我的C语言非常糟糕)。为此,最简单的解决方案是通过将DOM dom导入SimpleXml来获取名称空间。也许是这样的:
DOM does not have such a function afaik. I've looked briefly at the source code of SimpleXml and I think it iterates the loaded XML and collects the namespaces (my C is very bad). The easiest solution would be to fetch the namespaces by importing the DOM dom into SimpleXml for this purpose. Maybe like this:
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获取所有名称空间。请参阅以下问题和答案:
You could also try to get all namespaces with XPath. See the following question and answers:
- How to retrieve namespaces in XML files using Xpath
这篇关于枚举PHP DOMDocument对象的注册名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!