开发者

Fastest way to build an XML request with jQuery

开发者 https://www.devze.com 2023-01-15 23:32 出处:网络
I am accessing a certain web service API which requires XML data in the request. For example, the API might be expecting:

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 r开发者_StackOverflow社区equest, 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;
0

精彩评论

暂无评论...
验证码 换一张
取 消