using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace IOStream
{
public class Person
{
public Person() { }
private int id;
private string name;
private string place;
public int Id
{
get { return id; }
set { id = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Place
{
get { return place; }
set { place = value; }
}
}
/*使用xml串行化将对象保存为xml数据*/
class StringTest
{
public static void Main()
{
Person p1 = new Person();
p1.Id = 1;
p1.Name = "小明";
p1.Place = "武汉";
Person p2 = new Person();
p2.Id = 2;
p2.Name = "许愿";
p2.Place = "南昌";
Person p3 = new Person();
p3.Id = 3;
p3.Name = "有娴心";
p3.Place = "成都";
Person[] ps ={ p1, p2, p3 };
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "people";
xRoot.Namespace = "http://www.xx.com";
xRoot.IsNullable = true;
XmlSerializer xSerial = new XmlSerializer(typeof(Person[]), xRoot);
string filename = @"c:\people.xml";
TextWriter writer = new StreamWriter(filename);
xSerial.Serialize(writer, ps);
Console.ReadLine();
}
}
}
运行结果如下:
<?xml version="1.0" encoding="utf-8"?>
<people xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.xx.com">
<Person>
<Id>1</Id>
<Name>小明</Name>
<Place>武汉</Place>
</Person>
<Person>
<Id>2</Id>
<Name>许愿</Name>
<Place>南昌</Place>
</Person>
<Person>
<Id>3</Id>
<Name>有娴心</Name>
<Place>成都</Place>
</Person>
</people>