创建具有多个命名空间的根XML节点

时间:2015-02-16 08:50:50

标签: javascript jquery xml backbone.js namespaces

我正在使用Restful服务使用Backbone.js。必须发布XML。 我想添加多个命名空间

当前的JS代码就像,

var nsp = "xmlns='http://services.xyz/xmlschema/common'";
var nsp2 = "xmlns:ns2='http://services.xyz/xmlschema/subscription'";

var doc = document.implementation.createDocument(nsp, "ns2:subscription", "");

但我希望XML根节点就像,

<ns2:subscription xmlns='http://services.xyz/xmlschema/common' 
xmlns:ns2='http://services.xyz/xmlschema/subscription'>..</ns2:subscription>

提前致谢。

1 个答案:

答案 0 :(得分:2)

元素节点只能有一个命名空间,但有多个命名空间定义。您可以将它们作为属性节点添加到xmlns命名空间中。仅当元素节点或其某个属性节点未使用命名空间时才需要这样做。

&#13;
&#13;
var xmlns = {
    common : "http://services.xyz/xmlschema/common",
    xmlns: "http://www.w3.org/2000/xmlns/",
    ns2 : "http://services.xyz/xmlschema/subscription",
    ns3 : "urn:ns3"
};

var dom = document.implementation.createDocument('', '', null);
// create node in namespace (adds namespace definition)
var node = dom.appendChild(dom.createElementNS(xmlns.ns2, 'ns2:subscription'));
// default namespace - simple xmlns attribute
node.setAttribute('xmlns', xmlns.common);
// other namespace - attribute in xmlns namespace
node.setAttributeNS(xmlns.xmlns, 'xmlns:ns3', xmlns.ns3);

document.getElementById('demo').textContent = (new XMLSerializer()).serializeToString(dom);
&#13;
<textarea id="demo" style="width: 100%; height: 5em;"></textarea>
&#13;
&#13;
&#13;