新建一个WebForm1.aspx页面
前台
View Code
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="usexml.WebForm1" %> 2 3 4 5 6 718 198 9 10
后台
View Code
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI; 6 using System.Web.UI.WebControls; 7 using System.Xml; 8 using System.IO; 9 using System.Xml.Serialization; 10 namespace usexml 11 { 12 public partial class WebForm1 : System.Web.UI.Page 13 { 14 protected void Page_Load(object sender, EventArgs e) 15 { 16 17 } 18 19 20 public class Cat 21 { 22 23 public string CatName; 24 25 public string CatSex; 26 27 [XmlArrayAttribute("Items")] 28 public catcolor[] CatColor; 29 30 public cattype CatType; 31 32 33 34 } 35 36 public class cattype 37 { 38 [XmlAttribute] 39 public string remark; 40 41 public string type1; 42 43 public string type2; 44 45 public string type3; 46 47 48 49 50 51 } 52 53 54 public class catcolor 55 { 56 57 public string color1; 58 59 public string color2; 60 61 public string color3; 62 63 64 65 66 } 67 ///68 /// 序列化XML文档 69 /// 70 private void GetItems() 71 { 72 73 74 75 cattype billcattype = new cattype(); 76 77 billcattype.remark = "猫的种类"; 78 79 billcattype.type1 = "黑猫警长"; 80 81 billcattype.type2 = "白猫警长"; 82 83 billcattype.type3 = "黄猫警长"; 84 85 catcolor billcatcolor = new catcolor(); 86 87 billcatcolor.color1 = "黑"; 88 89 billcatcolor.color2 = "白"; 90 91 billcatcolor.color3 = "黄"; 92 93 Cat cat = new Cat(); 94 95 cat.CatName = ""; 96 97 cat.CatSex = ""; 98 99 cat.CatType = billcattype; 100 101 catcolor[] items = { billcatcolor }; 102 cat.CatColor = items; 103 104 //保存xml文档的路径 105 string patch = Server.MapPath("Cat.xml"); 106 107 //用ser这个类创建一个XmlSerializer 108 XmlSerializer ser = new XmlSerializer(typeof(Cat)); 109 110 try 111 { 112 //Stream提供一般的视图,这里将在目录下创建一个xml文档 113 Stream str = new FileStream(patch, FileMode.Create, FileAccess.Write); 114 115 //把 str 和 cat 传进 Serialize中,将xml文档序列化 116 ser.Serialize(str, cat); 117 118 //关闭资源 119 str.Close(); 120 //释放资源 121 str.Dispose(); 122 123 Response.Write("序列化成功!"); 124 125 126 } 127 128 catch (Exception ex) 129 { 130 131 Response.Write(ex.Message); 132 133 134 } 135 136 137 138 finally 139 { } 140 141 142 143 144 } 145 146 ///147 /// 点击按钮生成xml文档 148 /// 149 /// 150 /// 151 152 protected void Button1_Click(object sender, EventArgs e) 153 { 154 155 156 //调用GetItems()方法 157 this.GetItems(); 158 159 160 161 } 162 } 163 }
点击按钮,序列化XML文档
得到结果
View Code
1 23 4 5 6 127 11黑 8白 9黄 1013 17黑猫警长 14白猫警长 15黄猫警长 16