我正在寻找一种将JavaScript对象序列化为XML的最佳方法,可以以Ajax方式进一步发送到服务器。
谷歌搜索我发现了一些像http://svn.mirekrusin.com/pub/javascript/to_xml/trunk/to_xml.js这样的选项,但有人证明了经验,可以推荐任何特定的库吗?
答案 0 :(得分:2)
答案 1 :(得分:0)
我不知道是否有框架会为你做这件事但是......
// Define class constructor
var SampleObject1 = function()
{
this.name = 'MySampleObject';
this.id = 1;
this.seed = 1.009;
this.createdAt = new Date();
this.obj = null;
};
// Create instance of serializer
var serializer = new Ant.Serializer();
// Register SampleObject1, so serializer gets to know how to deal with such objects
serializer.register('SampleObject1', SampleObject1);
// Create data that will be serialized
var object = new SampleObject1();
object.obj = new SampleObject1();
// Serialize and get string representation
var xml = serializer.save(object).toString();
// Displays (formatting is changed):
// <SampleObject1>
// <name type="string">MySampleObject</name>
// <id type="number">1</id>
// <seed type="number">1.009</seed>
// <createdAt>
// <Date value="2007-7-26T20:31:24.156"/>
// </createdAt>
// <obj>
// <SampleObject1>
// <name type="string">MySampleObject</name>
// <id type="number">1</id>
// <seed type="number">1.009</seed>
// <createdAt>
// <Date value="2007-7-26T20:31:24.156"/>
// </createdAt>
// <obj/>
// </SampleObject1>
// </obj>
// </SampleObject1>
WScript.echo(xml);
// Displays: MySampleObject
WScript.echo(serializer.load(xml).name);