Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to build an XML request with jQuery

I am accessing a certain web service API which requires XML data in the request. For example, the API might be expecting:

<?xml version="1.0" encoding="utf-8" ?>

<root>
    <a>1</a>
    <b>2</b>
</root>

What's the easiest way to build that XML request, possibly using jQuery? Is there any standard serializer that I can use to build a JS object and serialize it to XML? What's the idiomatic way to do this?

like image 953
Yuval Adam Avatar asked Oct 15 '22 00:10

Yuval Adam


2 Answers

You could you GSerializer API's to serialize and deserialize javascripts objects. Here is a sample code

var myObject = new MyObject(); // The object to serialize
var serializer = new GSerializer(); // The Serializer
var serializedXML = serializer.serialize(myObject, 'MyObject'); // Grab the serialized XML
var deserializedObject = serializer.deserialize(serializedXML); // Deserialize the object from the serialized XML string 

Refer this article for more details.

like image 108
Vinay B R Avatar answered Oct 16 '22 14:10

Vinay B R


One option I found (which I am currently using, pending no better option) is the json2xml plugin for jQuery.

Example usage:

var xmlHead = '<?xml version="1.0" encoding="utf-8" ?>';

var j = {
    a : '1',
    b : 'B',
    c : {
      m : 'm'
    }
};

var opts = {
  rootTagName : 'myRoot',
  nodes : ['a', 'b', 'c']
};

var xml = $.json2xml(j, opts);
var xmlData = xmlHead + xml;
like image 39
Yuval Adam Avatar answered Oct 16 '22 15:10

Yuval Adam