views:

74

answers:

2

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?

A: 

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.

Vinay B R
A: 

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;
Yuval A