C#实现XML序列化与反序列化攻略
当我们需要将C#对象序列化成XML或反序列化成C#对象时,可以使用XML序列化技术。以下是实现XML序列化和反序列化的步骤:
1. 建立C#类
首先我们需要定义C#类,这些类将被序列化和反序列化。在类中定义属性和方法。序列化时,需要使用[Serializable]
属性标记将类作为可序列化的。以下是示例代码:
[Serializable]
public class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
public List<string> Tags { get; set; }
}
2. 序列化实例
建立一个XmlSerializer
对象并使用Serialize()
方法将类序列化为XML。以下是一个示例:
MyClass myObject = new MyClass(){ Id = 1, Name = "Demo", Tags= new List<string>{"Tag1", "Tag2"}};
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
using (StreamWriter writer = new StreamWriter("myObject.xml"))
{
serializer.Serialize(writer, myObject);
}
3. 反序列化实例
建立一个XmlSerializer
对象并使用Deserialize()
方法将XML文件反序列化为C#对象。以下是一个示例:
MyClass myObject;
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
using (StreamReader reader = new StreamReader("myObject.xml"))
{
myObject = (MyClass)serializer.Deserialize(reader);
}
这是C#实现XML序列化和反序列化的基本步骤。我们可以根据需求添加额外的功能。
示例1
定义如下简单的类Test
,其中有两个属性分别为 foo
和bar
。
[Serializable]
class Test
{
public int foo { get; set; }
public string bar { get; set; }
}
序列化并保存:
Test test = new Test() { foo = 1, bar = "a string" };
XmlSerializer xs = new XmlSerializer(typeof(Test));
using (StreamWriter sw = new StreamWriter("test.xml"))
{
xs.Serialize(sw, test);
}
输出结果为:
<?xml version="1.0" encoding="utf-8"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<foo>1</foo>
<bar>a string</bar>
</Test>
反序列化:
Test test2;
using (StreamReader sr = new StreamReader("test.xml"))
{
test2 = (Test)xs.Deserialize(sr);
}
然后,test2应该符合初始的测试实例。
示例2
定义一个包含一个嵌套的类的类:
[Serializable]
public class Employee
{
public int id { get; set; }
public string name { get; set; }
public Address address { get; set; }
}
[Serializable]
public class Address
{
public string street { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
}
此时,需要对Address类与Employee类进行序列化。这是序列化的代码:
Employee employee = new Employee()
{
id = 1,
name = "Bob",
address = new Address() {street = "123 Main St", city = "Anytown", state = "CA", zip = "12345"}
};
XmlSerializer serializer = new XmlSerializer(typeof(Employee));
using (StreamWriter writer = new StreamWriter("employee.xml"))
{
serializer.Serialize(writer, employee);
}
这是反序列化代码:
Employee employee2;
XmlSerializer serializer = new XmlSerializer(typeof(Employee));
using (StreamReader reader = new StreamReader("employee.xml"))
{
employee2 = (Employee)serializer.Deserialize(reader);
}
最终,我们可以看到employee2对象与employee对象的值是一致的。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#实现XML序列化与反序列化 - Python技术站