最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Create XML DOM Element while keeping case sensitivity - Stack Overflow

programmeradmin1浏览0评论

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);

However, document.createElement("v:custProps") generates <v:custprops> as opposed to <v:custProps>. Is there anyway to escape this parsing?


Edit 1:

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.

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);

However, document.createElement("v:custProps") generates <v:custprops> as opposed to <v:custProps>. Is there anyway to escape this parsing?


Edit 1:

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.

Share Improve this question edited Nov 17, 2014 at 21:27 Xenyal asked Nov 17, 2014 at 20:08 XenyalXenyal 2,2232 gold badges30 silver badges52 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

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>

It's not remended to use document.createElement for qualified names. See if the document.createElementNS can better serve your purposes.

I still had issues where createElementNs would attach an attribute of "xmls" on my string about using new XMLSerializer().serializeToString(xmlDoc).

I ended up using the following function to create elements with case sensitive tag names:

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

评论列表(0)

  1. 暂无评论