【问题标题】:Create root XML node with more than 1 namespace创建具有超过 1 个命名空间的根 XML 节点
【发布时间】:2015-04-16 17:41:57
【问题描述】:

我正在使用带有 Restful 服务的 Backbone.js。必须发布 XML。 我想添加超过 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>

提前致谢。

【问题讨论】:

    标签: javascript jquery xml backbone.js namespaces


    【解决方案1】:

    一个元素节点只能有一个命名空间,但可以有多个命名空间定义。您可以将它们作为属性节点添加到 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);
    &lt;textarea id="demo" style="width: 100%; height: 5em;"&gt;&lt;/textarea&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-14
      • 2021-08-08
      • 1970-01-01
      相关资源
      最近更新 更多