XML节点:使用命名空间添加属性 [英] XML node: add an attribute with a namespace

查看:152
本文介绍了XML节点:使用命名空间添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to add an attribute into an xml node. I have created the following function

  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中尝试过,它运行正常。

This code does not work in Firefox . It adds the node, but it does not add the namespace. I have tried in IE and in Chrome and it works fine.

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

Do you know how can I add the namespace? Or do you know any other alternative to create an attribute with a namespace?

谢谢

推荐答案

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

I have found a possible solution. At least it works now for the three browsers : IE, Firefox and 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的帮助。

Thanks to "Tomalak" for his help.

这篇关于XML节点:使用命名空间添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆