• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

c#XML序列化与反序列化

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

原先一直用BinaryFormatter来序列化挺好,可是最近发现在WinCE下是没有办法进行BinaryFormatter操作,很不爽,只能改成了BinaryWriterBinaryReader来读写,突然想到能不能用XML来序列化?于是在网上查了些资料便写了些实践性代码,做些记录,避免以后忘记。

 

序列化对象

 

    public class People

    {

        [XmlAttribute("NAME")]

        public string Name

        { set; get; }

        [XmlAttribute("AGE")]

        public int Age

        { set; get; }

    }

    [XmlRoot("Root")]

    public class Student : People

    {

        [XmlElement("CLASS")]

        public string Class

        { set; get; }

        [XmlElement("NUMBER")]

        public int Number

        { set; get; }

    }

 

void Main(string[] args)

 

{

 

            Student stu = new Student()

            {

                Age = 10,

                Class = "Class One",

                Name = "Tom",

                Number = 1

            };

            XmlSerializer ser = new XmlSerializer(typeof(Student));

            ser.Serialize(File.Create("C:\\x.xml"), stu);

 

}

 

反序列化对象

 

            XmlSerializer ser = new XmlSerializer(typeof(Student));

            Student stu = ser.Deserialize(File.OpenRead("C:\\x.xml")) as Student;

 

对象数组序列化

 

    public class People

    {

        [XmlAttribute("NAME")]

        public string Name

        { set; get; }

        [XmlAttribute("AGE")]

        public int Age

        { set; get; }

    }

    [XmlRoot("Root")]

    public class Student : People

    {

        [XmlElement("CLASS")]

        public string Class

        { set; get; }

        [XmlElement("NUMBER")]

        public int Number

        { set; get; }

    }

 

void Main(string[] args)

 

{

 

            List<Student> stuList = new List<Student>();

            stuList.Add(new Student() { Age = 10, Number = 1, Name = "Tom", Class = "Class One" });

            stuList.Add(new Student() { Age = 11, Number = 2, Name = "Jay", Class = "Class Two" });

            stuList.Add(new Student() { Age = 12, Number = 3, Name = "Pet", Class = "Class One" });

            stuList.Add(new Student() { Age = 13, Number = 4, Name = "May", Class = "Class Three" });

            stuList.Add(new Student() { Age = 14, Number = 5, Name = "Soy", Class = "Class Two" });

            XmlSerializer ser = new XmlSerializer(typeof(List<Student>));

            ser.Serialize(File.Create("C:\\x.xml"), stuList);

 

}

 

对象数组反序列

 

            XmlSerializer ser = new XmlSerializer(typeof(List<Student>));

            List<Student> stuList = ser.Deserialize(File.OpenRead("C:\\x.xml")) as List<Student>;

            foreach (Student s in stuList)

            {

                MessageBox.Show(string.Format("{0} : {1} : {2} : {3}",

                    s.Name, s.Age, s.Class, s.Number));

            }

 

序列化Dirctionary

 

    public struct DirectionList

    {

        [XmlAttribute("Name")]

        public string Name;

        [XmlElement("Value")]

        public int Value;

    }

 

void Main(string[] args)

 

{

 

            Dictionary<string, int> list = new Dictionary<string, int>();

            list.Add("1", 100);

            list.Add("2", 200);

            list.Add("3", 300);

            list.Add("4", 400);

            list.Add("5", 500);

            list.Add("6", 600);

            list.Add("7", 700);

            list.Add("8", 800);

            list.Add("9", 900);

 

            List<DirectionList> dirList = new List<DirectionList>();

            foreach (var s in list)

            {

                dirList.Add(new DirectionList() { Name = s.Key, Value = s.Value });

            }

            XmlSerializer ser = new XmlSerializer(typeof(List<DirectionList>));

            ser.Serialize(File.Create("C:\\x.xml"), dirList);

 

}

 

这里还要讲一点,在XmlSerializer中,不支持Dirctionary<>类型的对象,所以在序列化这种最常见类型的时候,只能按照它的格式先创建一个可以别序列化的类型,这里我定义了一个结构体,当然你也可以定义成其他的类。将Dictionary<>中的数据依次放进结构体以后就可以放入流中了。

 

[XmlAttribute("Name")]意思是将这个字段作为xml的属性,属性名跟在“”中

 

[XmlElement("Value")]意思是将这个字段做为xml的元素。

 

反序列化Dirctionary

 

 

            XmlSerializer ser = new XmlSerializer(typeof(List<DirectionList>));

            List<DirectionList> dirList = ser.Deserialize(

                File.OpenRead("C:\\x.xml")) as List<DirectionList>;

            foreach (var v in dirList)

            {

                Console.WriteLine("{0} : {1}", v.Name, v.Value);

            }

 

其实我并不喜欢这个名称,感觉有点生化危机的feel,但是也就是这样了,没有太炫的地方,Deserialize反序列化。真希望.Net能集成Dirctionary<>对象,那我们这些懒人就方便了。

 

在需要序列化的队伍中,数组是很常见的类型,其次就是图片了

 

序列化图片

 

    public struct ImageStruct

    {

        [XmlAttribute("Number")]

        public int number;

        [XmlElement("Image")]

        public byte[] picture;

    }

 

void Main(string[] args)

 

{

 

            ImageStruct s = new ImageStruct() { number = 1, picture = File.ReadAllBytes(@"11.jpg") };

            XmlSerializer ser = new XmlSerializer(typeof(ImageStruct));

            FileStream fs = File.Create("c:\\x.xml");

            ser.Serialize(fs, s);

            fs.Close();

 

}

 

一样的,采用结构体来保存图片,这里我还加了个图片的名字,到时候查找起来也方便一些

 

图片反序列化

 

            XmlSerializer ser = new XmlSerializer(typeof(ImageStruct));

            ImageStruct s = (ImageStruct)ser.Deserialize(File.OpenRead("c:\\x.xml"));

            pictureBox1.Image = Image.FromStream(new MemoryStream(s.picture));

 

没有花头的方式,利用memorystream来做缓存,这样会比较快一点,实际上我并没有怎么感觉。

 

图片数组序列化

 

    public struct ImageStruct

    {

        [XmlAttribute("Number")]

        public int number;

        [XmlElement("Image")]

        public byte[] picture;

    }

 

void Main(string[] args)

 

{

 

            List<ImageStruct> imageList = new List<ImageStruct>();

            imageList.Add(new ImageStruct()

            {

                number = 1,

                picture = File.ReadAllBytes(@"11.jpg")

            });

            imageList.Add(new ImageStruct()

            {

                number = 2,

                picture = File.ReadAllBytes(@"22.jpg")

            });

 

            XmlSerializer ser = new XmlSerializer(typeof(List<ImageStruct>));

            FileStream fs = File.Create("c:\\x.xml");

            ser.Serialize(fs, imageList);

            fs.Close();

 

}

 

图片数组反序列化

 

            XmlSerializer ser = new XmlSerializer(typeof(List<ImageStruct>));

            List<ImageStruct> s = (List<ImageStruct>)ser.Deserialize(File.OpenRead("c:\\x.xml"));

            var im = from i in s

                     where i.number == 1

                     select i.picture;

 

            //var im = s.Where(p => p.number == 1).Select(p => p.picture);

            foreach (var image in im)

            {

                pictureBox1.Image = Image.FromStream(

                    new MemoryStream(image));

            }

 

这里还对数组结构进行了Linq查询,这样就可以很方便的查询图片了。

 

--------------------------------------------------------------------------------------------------

 

要序列化的对象的类:

 

[Serializable]

public class Person

{

private string name;

public string Name

{

get

{

return name;

}

set

{

name=value;

}

}

public string Sex;

public int Age=31;

public Course[] Courses;

 

public Person()

{

}

public Person(string Name)

{

name=Name;

Sex="";

}

}

[Serializable]

public class Course

{

public string Name;

[XmlIgnore]public string Description;

public Course()

{

}

public Course(string name,string description)

{

Name=name;

Description=description;

}

 

 

进行序列化及反序列化的测试类:

 

class Test

{

//序列化

public void Serialiaze()

{

Person c=new Person("cyj")

c.Courses=new Course[2];

c.Courses[0]=new Course("英语","交流工具")

c.Courses[1]=new Course("数学","自然科学")

 

XmlSerializer xs=new XmlSerializer(typeof(Person));

Stream stream = new FileStream("c:\\cyj.xml", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);

xs.Serialize(stream, c);

stream.Close();

}

//反序列化

public void Deserialize()

{

XmlSerializer xs=new XmlSerializer(typeof(Person));

Stream stream = new FileStream("c:\\cyj.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

Person p=(Person)xs.Deserialize(stream);

Console.WriteLine(p.Name);

Console.WriteLine(p.Age.ToString());

Console.WriteLine(p.Courses.Length.ToString());

Console.Read();

}

}

格式化后Xml的文档内容为:

 

 

<?xml version="1.0"?>

<Person xmlns:xsd=http://www.w3.org/2001/XMLSchema    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

 <Sex></Sex>

   <Age>31</Age>

   <Courses>

     <Course>

       <Name>英语</Name>

     </Course>

     <Course>

       <Name>数学</Name>

     </Course>

   </Courses>

   <Name>cyj</Name>

</Person>

 

转自http://blog.csdn.net/ljsql/archive/2009/12/22/5057588.aspx


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#中使用事务发布时间:2022-07-13
下一篇:
【转】如何用UltraEdit编译C#源程序发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap