C#类对象转换成XML
要转换成xml的类
public class Student { public Student(){} public Student(string name,int age,int sex) { this.name=name; this.age=age; this.sex=sex; } private int age; private string name; private int sex; }
把对象保存成xml
private void objToXml() { Student s = new Student("John",24,1); XmlSerializer xs = new XmlSerializer(s.GetType()); TextWriter tw=new StreamWriter("C:/Myxml.xml"); xs.Serialize(tw,s); tw.Close(); }
保存的Myxml.xml内容如下
<?xml version=”1.0″ encoding=”utf-8″?> <Student xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema”>
可以看到xml文件中并没有我们保存的类信息,这是由于Student类中用的是字段,把字段封装成属性后得到如下结果:
<?xml version=”1.0″ encoding=”utf-8″?> <Student xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema”> <Age>24</Age> <Name>Joss</Name> <Sex>1</Sex> </Student>