我正在尝试创建以下元素节点树:
<v:custProps>
<v:cp v:nameU="Cost">
</v:custProps>
与:
newCustprop = document.createElement("v:custProps");
newcp = document.createElement("v:cp");
newcp.setAttribute("v:nameU", "Cost");
newCustprop.appendChild(newcp);
然而,document.createElement("v:custProps")
生成 <v:custprops>
而不是 <v:custProps>
.无论如何要逃避这种解析?
编辑 1:
我正在阅读 this关于节点名称区分大小写的文章。这与我的问题有点无关,因为我的代码未使用 <![CDATA]]>
进行解析。我宁愿不使用 .innerHTML
.
最佳答案
您需要使用 createElementNS()
/setAttributeNS()
并提供命名空间,而不仅仅是别名/前缀。该示例使用 urn:v
作为命名空间。
var xmlns_v = "urn:v";
var newCustprop = document.createElementNS(xmlns_v, "v:custProps");
var newcp = document.createElementNS(xmlns_v, "v:cp");
newcp.setAttributeNS(xmlns_v, "v:nameU", "Cost");
newCustprop.appendChild(newcp);
var xml = (new XMLSerializer).serializeToString(newCustprop);
xml:
<v:custProps xmlns:v="urn:v"><v:cp v:nameU="Cost"/></v:custProps>
关于javascript - 创建 XML DOM 元素同时保持区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26981034/