且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

getAttributeNS的行为是什么?

更新时间:2021-10-16 23:22:43

重要的是,> 属性只有在您明确为其命名空间之前,才能获得名称空间

The important thing is that attributes don't get the namespace until you explicitly prefix them with it:

默认名称空间声明适用于其范围内的所有未前缀元素名称。默认名称空间声明不能直接应用于属性名称

这不同于从父级继承默认名称空间的元素,除非已定义了自己的名称空间。话虽如此,您的属性没有命名空间,这就是为什么 getAttribute() getAttributeNS()有效的原因

This is unlike elements that do inherit the default namespace from the parent unless have their own defined. With that said, your attributes are not namespaced and that's why getAttribute() works and getAttributeNS() with a namespace value doesn't.

您的源XML需要看起来像这样来命名属性:

Your source XML would need to look something like this to "namespace" the attribute:

<a:query xmlns:a="jabber:iq:roster">
    <a:item a:subscription="both" a:jid="romeo@example.com"></a:item>
</a:query>

有关此主题的更多信息: XML名称空间和属性

Here's some more on the subject: XML namespaces and attributes.

如果您只想使用支持名称空间的方法,则应该(但不确定,可能是特定于实现的)可以为您使用 null 命名空间。尝试 getAttributeNS(null, jid)。如果不是这样,您始终可以使用 hasAttributeNS()来解决,然后回退到 getAttributeNS() getAttribute()

If you want to only use the namespace-aware methods then it should (not sure though, might be implementation specific) work for you with null namespace. Try getAttributeNS(null, "jid"). If it doesn't, you can always work around it with the hasAttributeNS() and only then a fallback to getAttributeNS() or getAttribute().