jquery .append() case sensitive element

2019-01-26 17:38发布

问题:

Hi I need to create xml from data in form to send it to webservice. The problem is that .append() is case insensitive, so .append('<EDO />') will create <edo>. But xml is case sensitive, so is there a way how to solve this? And I've chosen to use domObject instead of string, because this way I don't have to write endtags, what would be very difficult in my scenario.

回答1:

Try using $.parseXML() to create the XML element:

yourObject.append($.parseXML("<EDO />").documentElement);


回答2:

Finally as @Frédéric Hamidi said, to make case sensitive xml I used these functions:

var domA = $.parseXML("<EDO_A />").documentElement; to create element

$(domA ).append($.parseXML('<EDO_Child />').documentElement); to add child from string

$(domA).append(domB) or domA.appendChild(domB) to add child object



回答3:

jQuery.parseXML will always create a new DOMParse and a new Document, so it is pretty heavy.

A better approach would be to use the (unintuitive) parseHTML, using the context paramter:

// Create the context XML document; doc and $doc is reusable
var doc = (new DOMParser()).parseFromString( '<root/>', 'text/xml' ); 
var $doc = $( doc.documentElement )

// Create case-sensitive XML element;
// this will call doc.createElement( 'EDO' ), as of jQuery 2.1.3
$doc.append( $.parseHTML( '<EDO />', doc ) ); 


回答4:

Notes:

$.parseHTML("<AddPerson>Adel</AddPerson>"); //result: <addperson>Adel</addperson>

$.parseXML("<AddPerson>Adel</AddPerson>"); //result: <AddPerson xmlns="">Adel</AddPerson>

I guess that you need these lines:

var request = $.parseXML(HtmlOrXmlStringSource);
$(request).find(someElementInside).append(HtmlOrXmlStringSource_2);

//Serialize XML
var oSerializer = new XMLSerializer();
request = oSerializer.serializeToString(request);
request = request.replace(new RegExp(' xmlns=""', "igm"), "");

Now the request is ready to be sent through $.ajax();

Thanks