使用XML串行化就可以將類的實例轉換為XML,反之亦然。開發人員經常需要進行XML穿行化。
程序清單中展示了一個串行化的實例。第一步是創建 Person 類的實例,並用進行初始化。然後利用XMLSerializer將Person 類的這個實例串行化。 using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/**//// <summary>
/// Person 的摘要說明
/// </summary>
public class Person
{
public Person()
{
//
// TODO: 在此處添加構造函數邏輯
//
}
public string Name
{
set
{
_name = value;
}
get
{
return _name;
}
} private string _name;
public int Age
{
set
{
_age = value;
}
get
{
return _age;
}
} private int _age;
}
<%@ Page Language="C#" %>
<%@ Import Namespace="System.XML.Serialization" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Person person = new Person();
person.Name = "☆聊ゾ聊☆";
person.Age = 23;
//Response.Clear();
//Response.ContentType = "text/XML";
XmlSerializer serializer = new XMLSerializer(person.GetType());
serializer.Serialize(Response.OutputStream, person);
}
</script>
運行後得到的結果: <?XML version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" XMLns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>☆聊ゾ聊☆</Name>
<Age>23</Age>
</Person>
自定義串行化。假設需要把某個類的一個共有屬性轉換為 XML 屬性,那麼上面的做法就無法滿足要求了。為了達到這一目的,我們可以實現自定義的XML串行化。程序清單如下: using System;
using System.XML.Serialization;
[XMLRoot("員工")]
public class Employee
{
public Employee()
{
}
[XMLAttribute("姓名")]
public string Name
{
set
{
_name = value;
}
get
{
return _name;
}
} private string _name;
[XMLAttribute("年齡")]
public int Age
{
set
{
_age = value;
}
get
{
return _age;
}
} private int _age;
[XMLElement("備注")]
public string Remarks
{
set
{
_remarks = value;
}
get
{
return _remarks;
}
} private string _remarks;
}
<%@ Page Language="C#" %>
<%@ Import Namespace="System.XML.Serialization" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Employee employee = new Employee();
employee.Name = "☆聊ゾ聊☆";
employee.Age = 23;
employee.Remarks = "☆聊ゾ聊☆ ☆聊ゾ聊☆ ☆聊ゾ聊☆ ☆聊ゾ聊☆ ☆聊ゾ聊☆";
//Response.Clear();
//Response.Conte
ntType = "text/XML";
XmlSerializer serializer = new XMLSerializer(employee.GetType());
serializer.Serialize(Response.OutputStream, employee);
}
</script>
運行結果: <?XML version="1.0"?>
<員工 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" 姓名="☆聊ゾ聊☆" 年齡="23">
<備注>☆聊ゾ聊☆ ☆聊ゾ聊☆ ☆聊ゾ聊☆ ☆聊ゾ聊☆ ☆聊ゾ聊☆</備注>
</員工>
http://www.cnblogs.com/hblynn/archive/2007/02/09/646403.Html