关于XMLSerialization对复杂类的读和写

本文介绍了一个使用C#进行XML序列化的示例,包括如何将含有子类的对象序列化为XML文件,并演示了如何从XML文件反序列化回对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近,为了将一个窗口内所有控件的值保存到一个XML文件中,得研究一个如何将一个类的值全部保存到一个XML文件中的例子。

于是google
http://msdn.microsoft.com/en-us/4kaaezfd(v=vs.90)
得到了这个地址,非常好,详细地给出了读写简单类的方法。

可惜,在进行复杂类的写入的时候,就是一个类内有另外一个的时候,出问题了,于是继续g
得到了 http://blog.youkuaiyun.com/menglin2010/article/details/7165553
这个例子。非常好,但是没有关于读的内容,于是,对微软的例子进行了一定的修改之后。内容如下。

学生类 student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConsoleApplication1;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
public class student
{
//学生名字
private string _name;
[XmlElement]
public string name
{
get { return _name; }
set { _name = value; }
}
//学生年龄
private string _age = "";
[XmlElement]
public string age
{
get { return _age; }
set { _age = value; }
}
}
}



写出XML文件

using System;
using System.Collections.Generic;
using ConsoleApplication1;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
[Serializable()]
[XmlRoot]
public class Book
{
public string title;
public int page;
public student sname;
public Book()
{
}
private static void Main()
{
Book introToVCS = new Book();
introToVCS.title = "Intro to Visual CSharp";
introToVCS.page = 26;
introToVCS.sname = new student();
introToVCS.sname.name = "xixi";
introToVCS.sname.age = "15";
System.Xml.Serialization.XmlSerializer writer =
new System.Xml.Serialization.XmlSerializer(
introToVCS.GetType());
System.IO.StreamWriter file =
new System.IO.StreamWriter("c:\\IntroToVCS.xml");
writer.Serialize(file, introToVCS);
file.Close();
}
}
}



读入XML文件

using System;
//http://msdn.microsoft.com/en-us/4kaaezfd(v=vs.90)
using ConsoleApplication1;
public class Book
{
public string title;
public int page;
public student sname;
public Book()
{
}
static void Main()
{
Book introToVCS = new Book();
System.Xml.Serialization.XmlSerializer reader = new
System.Xml.Serialization.XmlSerializer(introToVCS.GetType());
// Read the XML file.
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\IntroToVCS.xml");
// Deserialize the content of the file into a Book object.
introToVCS = (Book)reader.Deserialize(file);
System.Windows.Forms.MessageBox.Show(introToVCS.title, "Book Title");
System.Windows.Forms.MessageBox.Show(System.Convert.ToString(introToVCS.page), "Book PAGES");
System.Windows.Forms.MessageBox.Show(System.Convert.ToString(introToVCS.sname.name), "NAME");
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值