Welcome

首页 / 脚本样式 / Ajax / ASP.NET 2.0 Ajax - 以XML方式序列化数据

ASP.NET 2.0 Ajax - 以XML方式序列化数据2011-09-27第2章中曾经提到过,ASP.NET AJAX异步通信层在传递数据时默认采用JSON序列化方式,但同时也提供给我们以XML方式进行序列化的选项。

一般来讲,如果某Web Service方法的返回值类型为XmlDocument或XmlElement,我们应该让这类返回值以XML方式进行序列化。例如如下的这个Web Service方法:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public XmlDocument GetXmlDocument()
{
string theString = "<persons>"
+ "<person><name>Tom</name><age>30</age></person>"
+ "<person><name>Jerry</name><age>20</age></person>"
+ "</persons>";

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(theString());
return xmlDoc;
}

注意上述代码中的粗体部分,[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]这个属性就将该GetXmlDocument()方法返回值的序列化方式设置为了XML。在客户端的回调函数中,返回的客户端XML文档对象在Visual Studio调试器中显示出的结构如图3-36所示。

图3-36 服务器端XmlDocument类型在客户端的结构

在客户端得到返回的XML文档对象之后,我们即可根据需求对其进行操作,限于篇幅,这里不赘。

对于非XmlDocument或XmlElement的类型,如果我们愿意,也可以选择将其以XML的方式进行序列化。我们还是以前面定义的Employee类为例,如下Web Service方法就以XML序列化的方式返回一个Employee对象:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public Employee GetXMLFormatEmployee()
{

return new Employee(
12345,
"Dflying",
"Dflying@some.com",
int.MaxValue
);
}