XML序列化和反序列化示例

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;


namespace IPTool
{
    [XmlRoot(ElementName="ChinaIPArea")]
    public class ChinaIPAreaInfo
    {
        [XmlElement(ElementName = "IPArea")]
        public List<IPArea> ChinaIPAreaList = new List<IPArea>();

        public static ChinaIPAreaInfo GetChinaIPAreaInfo(string path)
        {
            string content;
            using (StreamReader reader = new StreamReader(path, Encoding.UTF8))
            {
                content = reader.ReadToEnd();
            }

            if (string.IsNullOrEmpty(content.Trim()))
                return null;

            ChinaIPAreaInfo ipInfo = ChinaIPAreaInfo.Create(content);

            return ipInfo;
        }

        public static ChinaIPAreaInfo Create(string str)
        {
            if (str == null || str.Length <= 0)
                return null;

            using (StringReader reader = new StringReader(str))
            {
                XmlSerializer xs = new XmlSerializer(typeof(ChinaIPAreaInfo));
                ChinaIPAreaInfo tmp = (ChinaIPAreaInfo)xs.Deserialize(reader);

                return tmp;
            }
        }

        public override string ToString()
        {
            using (MemoryStream writer = new MemoryStream())
            {
                Encoding encoding = new UTF8Encoding(false);
                using (XmlTextWriter ser = new XmlTextWriter(writer, encoding))
                {
                    XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
                    xsn.Add(String.Empty, String.Empty);
                    XmlSerializer xs = new XmlSerializer(this.GetType());
                    xs.Serialize(ser, this, xsn);
                    ser.Flush();
                    byte[] buffer = writer.ToArray();
                    return encoding.GetString(buffer);
                }
            }
        }
    }

    public class IPArea
    {
        [XmlElement(ElementName = "IPStart")]
        public int IPStart;

        [XmlElement(ElementName = "IPEnd")]
        public int IPEnd;
    }
}

posted @ 2010-05-21 17:44  Jack Tang  阅读(227)  评论(0编辑  收藏  举报