Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create XML DOM Element while keeping case sensitivity

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.

like image 939
Xenyal Avatar asked Nov 17 '14 20:11

Xenyal


People also ask

Are XML elements case-sensitive?

XML tags are case sensitive.

Is Dom a case-sensitive language?

Yes. It is case-sensitive. Attribute values are always case-sensitive.

Why XML is case-sensitive language?

XML is Case-Sensitive! The reason for the case-sensitivity is simple: internationalization. English is one of the few languages in the world where it's easy and straightforward to map upper- and lower-case letters together.

Is DTD case-sensitive?

Values defined explicitly by the DTD are case-insensitive.


2 Answers

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>
like image 184
ThW Avatar answered Oct 13 '22 17:10

ThW


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

like image 23
glifchits Avatar answered Oct 13 '22 16:10

glifchits