首页 > 代码库 > C#对象序列化成XML,以及自定义标签名

C#对象序列化成XML,以及自定义标签名

C#对象序列化操作:

public class XMLHelper{    /// <summary>    /// 对象序列化成 XML String    /// </summary>    public static string XmlSerialize<T>(T obj)    {        string xmlString = string.Empty;        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));        //using (TextWriter textWriter = new StreamWriter("D:\\xmlTest.xml"))        //{        //    xmlSerializer.Serialize(textWriter, obj);        //}        using (MemoryStream ms = new MemoryStream())        {            xmlSerializer.Serialize(ms, obj);            xmlString = Encoding.UTF8.GetString(ms.ToArray());        }        return xmlString;    }    /// <summary>    /// XML String 反序列化成对象    /// </summary>    public static T XmlDeserialize<T>(string xmlString)    {        T t = default(T);        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));        using (Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))        {            using (XmlReader xmlReader = XmlReader.Create(xmlStream))            {                Object obj = xmlSerializer.Deserialize(xmlReader);                t = (T)obj;            }        }        return t;    }}

示例:

[Serializable][XmlType(TypeName = "MySong")]public class Song{    [XmlElement("A")]    public string Artist;    [XmlElement("S")]    public string SongTitle;}class XMLDemo{    static void Main(string[] args)    {        List<Song> list = new List<Song>()        {            new Song(){ SongTitle="歌曲标题1",Artist="歌手1"},            new Song(){ SongTitle="歌曲标题2",Artist="歌手2"},            new Song(){ SongTitle="歌曲标题3",Artist="歌手3"}        };        string xmlString = XMLHelper.XmlSerialize(list);        /*<?xml version="1.0"?>        <ArrayOfSong xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">          <Song>            <Artist>歌手1</Artist>            <SongTitle>歌曲标题1</SongTitle>          </Song>          <Song>            <Artist>歌手2</Artist>            <SongTitle>歌曲标题2</SongTitle>          </Song>          <Song>            <Artist>歌手3</Artist>            <SongTitle>歌曲标题3</SongTitle>          </Song>        </ArrayOfSong>                 // 自定义标签名        <?xml version="1.0"?>        <ArrayOfMySong xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">          <MySong>            <A>歌手1</A>            <S>歌曲标题1</S>          </MySong>          <MySong>            <A>歌手2</A>            <S>歌曲标题2</S>          </MySong>          <MySong>            <A>歌手3</A>            <S>歌曲标题3</S>          </MySong>        </ArrayOfMySong>        */        Console.WriteLine(xmlString);    }}

 

C#对象序列化成XML,以及自定义标签名