问题描述
我正在尝试创建以下元素nodetree:
I'm trying to create the following element nodetree:
<v:custProps>
<v:cp v:nameU="Cost">
</v:custProps>
with:
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>
。无论如何都要逃避这种解析?
However, document.createElement("v:custProps")
generates <v:custprops>
as opposed to <v:custProps>
. Is there anyway to escape this parsing?
编辑1:
我正在阅读关于nodename案例敏感性的文章。这与我的问题有点无关,因为我的代码未解析为<![CDATA]]>
而我宁愿不使用 .innerHTML
。
I'm currently reading this article on nodename case sensitivity. It's slightly irrelevant to my problem though because my code is unparsed with <![CDATA]]>
and I'd rather not use .innerHTML
.
推荐答案
您需要使用 createElementNS()
/ setAttributeNS()
并提供命名空间,而不仅仅是别名/前缀。该示例使用 urn:v
作为命名空间。
You need to use createElementNS()
/setAttributeNS()
and provide the namespace, not only the alias/prefix. The example uses urn:v
as namespace.
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>
这篇关于创建XML DOM元素,同时保持区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!