XmlSerializer 可以用幫助我們將文件或內容轉成 XML 格式,也可利用 Deserializer 方法轉回原先格式。以下提供一個飯粒範例說明:
C#:
using System.Xml.Serialization;
using XMLPractice; // 自訂 namespace
namespace XMLPractice
{
[XmlRoot("RootList")]
public class RootClass
{
[XmlArray("AuthorList")]
public Author[] At; // 包含了 Author 作者類別
[XmlArray("List")]
public Items[] Ie; // 包含了 Items作者類別
}
public class AuthorEx
{
[XmlAttribute("id")] // 建立屬性 id
public int ele_id;
[XmlText()] // 建立內容 value 就是結果中的 皮皮、球球 二人組
public string ele_name;
}
public class Items
{
[XmlText()]
public string itmes_name;
}
}
try
{
//Serialization of String Object
RootClass Rclass = new RootClass { At = new[] { new Author{ ele_id = 1, ele_name = "皮皮" }, new Author{ele_id = 2, ele_name = "球球"} } };
Rclass.Ie = new[] { new Items { itmes_name = "Taipei" }, new Items { itmes_name = "TaiChung"},new Items { itmes_name = "Kaoshung" } };
FileStream stream = new FileStream("D:\\Example.txt", FileMode.Create, FileAccess.Write,
FileShare.None); // 建立文件檔
XmlSerializer xmlserializer = new XmlSerializer(typeof(RootClass)); // 序列化 RootClass 類列物件
xmlserializer.Serialize(stream, Rclass);
stream.Close();
}
結果 ( 打開 D:\Example.txt 就可以看到如下的結果):
<?xml version="1.0"?>
<RootList>
<AuthorList>
<Author id="1">皮皮</Author>
<Author id="2">球球</Author>
</AuthorList>
<List>
<Item>Taipei</Item>
<Item>TaiChung</Item>
<Item>Kaoshung</Item>
</List>
</RootList>
C#:
using System.Xml.Serialization;
using XMLPractice; // 自訂 namespace
namespace XMLPractice
{
[XmlRoot("RootList")]
public class RootClass
{
[XmlArray("AuthorList")]
public Author[] At; // 包含了 Author 作者類別
[XmlArray("List")]
public Items[] Ie; // 包含了 Items作者類別
}
public class AuthorEx
{
[XmlAttribute("id")] // 建立屬性 id
public int ele_id;
[XmlText()] // 建立內容 value 就是結果中的 皮皮、球球 二人組
public string ele_name;
}
public class Items
{
[XmlText()]
public string itmes_name;
}
}
try
{
//Serialization of String Object
RootClass Rclass = new RootClass { At = new[] { new Author{ ele_id = 1, ele_name = "皮皮" }, new Author{ele_id = 2, ele_name = "球球"} } };
Rclass.Ie = new[] { new Items { itmes_name = "Taipei" }, new Items { itmes_name = "TaiChung"},new Items { itmes_name = "Kaoshung" } };
FileStream stream = new FileStream("D:\\Example.txt", FileMode.Create, FileAccess.Write,
FileShare.None); // 建立文件檔
XmlSerializer xmlserializer = new XmlSerializer(typeof(RootClass)); // 序列化 RootClass 類列物件
xmlserializer.Serialize(stream, Rclass);
stream.Close();
}
結果 ( 打開 D:\Example.txt 就可以看到如下的結果):
<?xml version="1.0"?>
<RootList>
<AuthorList>
<Author id="1">皮皮</Author>
<Author id="2">球球</Author>
</AuthorList>
<List>
<Item>Taipei</Item>
<Item>TaiChung</Item>
<Item>Kaoshung</Item>
</List>
</RootList>
留言
張貼留言