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?
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With