XML节点:添加具有命名空间的属性

XML node: add an attribute with a namespace

本文关键字:命名空间 属性 节点 添加 XML      更新时间:2023-09-26

我正在尝试将属性添加到xml节点中。我创建了以下功能

  function AddAttribute(xmlNode, attrname, attrvalue, path) {
    var attr;
    if (isIE())
        attr = xmlNode.ownerDocument.createNode(2, attrname, "http://mydomain/MyNameSpace");
    else
        attr = xmlNode.ownerDocument.createAttributeNS("http://mydomain/MyNameSpace", attrname);
    attr.nodeValue = attrvalue;
    var n = xmlNode.selectSingleNode(path);
    n.setAttributeNode(attr);
} 

此代码在Firefox中不起作用。它添加了节点,但没有添加命名空间。我试过IE和Chrome,效果很好。

你知道我该如何添加命名空间吗?或者,您知道创建具有名称空间的属性的其他选择吗?

感谢

我找到了一个可能的解决方案。至少它现在适用于三种浏览器:IE、Firefox和Chrome。

 function AddAttribute(xmlNode, attrname, attrvalue, path) {
    var attr;
    if (xmlNode.ownerDocument.createAttributeNS)
       attr = xmlNode.ownerDocument.createAttributeNS("http://www.firmglobal.com/MyNameSpace", attrname);
    else
       attr = xmlNode.ownerDocument.createNode(2, attrname, "http://www.firmglobal.com/MyNameSpace");
    attr.nodeValue = attrvalue;
    var n = xmlNode.selectSingleNode(path);
    //Set the new attribute into the xmlNode
    if (n.setAttributeNodeNS)
       n.setAttributeNodeNS(attr);  
    else
        n.setAttributeNode(attr);  
}

感谢"托马拉克"的帮助。