這種方法主要描述不使用Dataset也可以講資料移出Sql Server資料庫,和前者相比的有點在於減少從資料庫檢索所需要的代碼量。
1、Contact類代碼:
1: using System.Xml.Serialization;
2:
3: /// <summary>
4: /// Summary description for Contact
5: /// </summary>
6: ///
7: [XmlRoot("Contacts")]
8: public class Contact
9: {
10: public string ID;
11: public string FirstName;
12: public string MiddleName;
13: public string LastName;
14:
15: public Contact()
16: {
17: //
18: // TODO: Add constructor logic here
19: //
20: }
21: }
2、執行代碼:
1: using System;
2: using System.Web.Configuration;
3: using System.Xml;
4: using System.Xml.Serialization;
5: using System.Data.SqlClient;
6:
7: public partial class Default5 : System.Web.UI.Page
8: {
9: protected void Page_Load(object sender, EventArgs e)
10: {
11: Contact cont;
12: XmlElementAttribute contIDElement = new XmlElementAttribute();
13: contIDElement.ElementName = "ContactID";
14:
15: XmlAttributes attributesIdCol = new XmlAttributes();
16: attributesIdCol.XmlElements.Add(contIDElement);
17: XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
18: attrOverrides.Add(typeof(Contact),"ID",attributesIdCol);
19:
20: string connString = WebConfigurationManager.ConnectionStrings["AdventureWorks"].ConnectionString;
21: SqlConnection sqlConn = new SqlConnection(connString);
22: sqlConn.Open();
23: SqlCommand sqlCommand = new SqlCommand("select ContactID,"+ "FirstName, MiddleName, LastName, EmailAddress from Person.Contact "+ "as Contacts where ContactID=2 for XML Auto, elements", sqlConn);
24: XmlReader reader = sqlCommand.ExecuteXmlReader();
25: XmlSerializer serializer = new XmlSerializer(typeof(Contact), attrOverrides);
26: serializer.UnknownElement+=new
27: XmlElementEventHandler(XmlSerializer_UnknownElement);
28: if(serializer.CanDeserialize(reader))
29: {
30: cont=(Contact)serializer.Deserialize(reader);
31: Response.Write("<b>反序列化的結果是:" + "</b><br>");
32: Response.Write("ID: " + cont.ID + "<br/>");
33: Response.Write("FirstName: " + cont.FirstName + "<br/>");
34: Response.Write("FirstName: " + cont.MiddleName+ "<br/>");
35: Response.Write("FirstName: " + cont.LastName + "<br/>");
36:
37: }
38: else
39: {
40: Response.Write("檔案不能進行反序列化處理!");
41: }
42: }
43:
44: /// <summary>
45: /// Handles the UnknownElement event of the XmlSerializer control.
46: /// </summary>
47: /// <param name="sender">The source of the event.</param>
48: /// <param name="e">The <see cref="System.Xml.Serialization.XmlElementEventArgs"/> instance containing the event data.</param>
49: void XmlSerializer_UnknownElement(object sender, XmlElementEventArgs e)
50: {
51: Response.Write("Unknown Element:" + "<br/>");
52: Response.Write("Unknown Element Name: " + e.Element.Name + "<br/>");
53: Response.Write("Unknown Element Value: " + e.Element.InnerText + "<br/>");
54: }
55: }
3、執行結果