创建具有超过 1 个命名空间的根 XML 节点

Create root XML node with more than 1 namespace

我正在使用 Backbone.js 和 Restful 服务。得postXML。 我想添加超过 1 个命名空间

当前的 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>

提前致谢。

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

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);
<textarea id="demo" style="width: 100%; height: 5em;"></textarea>