XML节点:使用命名空间添加属性

时间:2012-02-06 12:54:41

标签: javascript xml

我正在尝试将属性添加到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中试过了,它运行正常。

您知道如何添加命名空间吗? 或者您是否知道使用命名空间创建属性的其他替代方法?

由于

1 个答案:

答案 0 :(得分:1)

我找到了一个可能的解决方案。至少它适用于三种浏览器: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);  
}

感谢“Tomalak”的帮助。