在保持大小写敏感性的情况下创建XML DOM元素

7

我正在尝试创建以下元素节点树:

<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: 我目前正在阅读有关节点名称区分大小写的文章(链接),但我的代码未经解析,使用<! [CDATA]]>,我宁愿不使用.innerHTML
3个回答

6

您需要使用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>

2

不建议使用document.createElement来创建限定名称。请查看document.createElementNS是否更适合您的需求。


1
".createElementNS" 似乎缺少 XML 元素的命名空间.. 我已经测试过了,生成的 JavaScript 返回一个不区分大小写的结果。 - Xenyal

1

我仍然遇到了一个问题,即createElementNs会在使用new XMLSerializer().serializeToString(xmlDoc)时,将一个名为"xmls"的属性附加到我的字符串上。

最终,我使用了以下函数来创建区分大小写标记名称的元素:

function createElement(tagName) {
  const doc = new DOMParser().parseFromString(`<${tagName}></${tagName}>`, 'text/xml')
  return doc.children[0]
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接