using System.Xml.Serialization;
<BaseInfo>
<Person>
<Name>张三</Name>
<Age>11</Age>
<Person>
<Books>
<IsBN>111</IsBN>
<Title>book1</Title>
</Books>
<Books>
<IsBN>222</IsBN>
<Title>book2</Title>
</Books>
</Person>
</Person>
<Person>
<Name>李四</Name>
<Age>22</Age>
<Person>
<Books>
<IsBN>333</IsBN>
<Title>book3</Title>
</Books>
</Person>
</Person>
</BaseInfo>
1.对象序列化为XML文档
建立对象:
book类:
public class Book
{
private string _isbn;
private string _title;
public Book() { }
public Book(string isbn, string title)
{
this._isbn = isbn;
this._title = title;
}
public string IsBN
{
get
{
return _isbn;
}
set
{
_isbn = value;
}
}
public string Title
{
get { return _title; }
set { _title = value; }
}
}
books类:
public class Books
{
private List<Book> _bookList = new List<Book>();
[XmlElement(ElementName="Books")]
public List<Book> BookList
{
get { return _bookList; }
set { _bookList = value; }
}
}
person类:
public class Person
{
private string _name;
private int _age;
private List<Books> _bookList = new List<Books>();
public Person() { }
public Person(string name, int age)
{
this._name = name;
this._age = age;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public int Age
{
get { return _age; }
set { _age = value; }
}
[XmlElement(ElementName="Person")]
public List<Books> BookList
{
get { return _bookList; }
set { _bookList = value; }
}
}
BaseInfo类:
public class BaseInfo
{
private List<Person> _personList = new List<Person>();
[XmlElement(ElementName="Person")]
public List<Person> PersonList
{
get { return _personList; }
set { _personList = value; }
}
}
序列化成对象:
static void XmlSerierizer()
{
Book b1 = new Book("111","book1");
Book b2 = new Book("222", "book2");
Book b3 = new Book("333", "book3");
Books bs1 = new Books();
Books bs2 = new Books();
bs1.BookList.Add(b1);
bs1.BookList.Add(b2);
bs2.BookList.Add(b3);
Person p1 = new Person("张三", 11);
Person p2 = new Person("李四", 22);
p1.BookList.Add(bs1);
p2.BookList.Add(bs2);
BaseInfo baseInfo = new BaseInfo();
baseInfo.PersonList.Add(p1);
baseInfo.PersonList.Add(p2);
using (StringWriter writer = new StringWriter())
{
XmlSerializerNamespaces ns=new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer serializer = new XmlSerializer(typeof(BaseInfo));
serializer.Serialize(writer, baseInfo, ns);
string path="Students.xml";
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
byte[] buffer = Encoding.UTF8.GetBytes(writer.ToString());
fs.Write(buffer, 0, buffer.Length);
}
}
}
或: //序列化 public static string ObjectToXmlSerializer(Object Obj) { string XmlString = ""; XmlWriterSettings settings = new XmlWriterSettings(); //去除xml声明 //settings.OmitXmlDeclaration = true; settings.Indent = true; settings.Encoding = Encoding.Default; using (System.IO.MemoryStream mem = new MemoryStream()) { using (XmlWriter writer = XmlWriter.Create(mem, settings)) { //去除默认命名空间xmlns:xsd和xmlns:xsi XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer formatter = new XmlSerializer(Obj.GetType()); formatter.Serialize(writer, Obj, ns); } XmlString = Encoding.Default.GetString(mem.ToArray()); } return XmlString; }
2.将XML文档反序列化为对象
static void xmlDeserialize()
{
//xml来源可能是外部文件,也可能是从其他系统获得
FileStream file = new FileStream(@"Students.xml", FileMode.Open, FileAccess.Read);
XmlSerializer xmlSearializer = new XmlSerializer(typeof(BaseInfo));
BaseInfo info = (BaseInfo)xmlSearializer.Deserialize(file);
file.Close();
foreach (Person per in info.PersonList)
{
Console.WriteLine("人员:");
Console.WriteLine(" 姓名:" + per.Name);
Console.WriteLine(" 年龄:" + per.Age);
foreach (Books b1 in per.BookList)
{
foreach (Book b in b1.BookList)
{
Console.WriteLine(" 书:");
Console.WriteLine(" ISBN:" + b.IsBN);
Console.WriteLine(" 书名:" + b.Title);
}
}
}
Console.ReadKey();
}
或: //反序列化Xml public static T ObjectToXmlDESerializer<T>(string str) where T : class { object obj; using (System.IO.MemoryStream mem = new MemoryStream(Encoding.Default.GetBytes(str))) { using (XmlReader reader = XmlReader.Create(mem)) { XmlSerializer formatter = new XmlSerializer(typeof(T)); obj = formatter.Deserialize(reader); } } return obj as T; }
3.xml特性:
有时,我们在序列化时想要自定义XML的结构,这时候就要用到我们的属性类了。属性类提供了很多特性供我们使用,以完成自定义序列化功能。
名称 | 描述 |
XmlAttribute | 表示一个特性对象的集合,这些对象控制XmlSerializer如何序列化和反序列化对象 |
XmlArrayAttribute | 指定XmlSerializer应将特定的类成员序列化为XML元素数组 |
XmlArrayItemAttribute | 指定XmlSerializer可以放置在序列化数组中的派生类型 |
XmlArrayItemAttributes | 表示XmlArrayItemAttribute对象的集合 |
XmlAttributeAttribute | 指定XmlSerializer应将类成员作为XML特性序列化 |
XmlChoiceIdentifierAttribute | 指定可以通过使用枚举来进一步消除成员的歧义 |
XmlElementAttribute | 在XmlSerializer序列化或反序列化包含对象时,指示公共字段或属性表示XML元素 |
XmlElementAttributes | 表示XmlElementAttribute的集合,XmlSerializer将其用于它重写序列化类的默认方式 |
XmlEnumAttribute | 控制XmlSerializer如何序列化枚举成员 |
XmlIgnoreAttribute | 指示XmlSerializer方法不序列化公共字段或公共读/写属性值 |
XmlIncludeAttribute | 允许XmlSerializer在它序列化或反序列化对象时识别类型 |
XmlRootAttribute | 控制视为XML根元素的属性目标的XML序列化 |
XmlTextAttribute | 当序列化或反序列化时,想XmlSerializer指示应将此成员作为XML文本处理 |
XmlTypeAttribute | 控制当属性目标由XmlSerializer序列化时生成的XML结构 |
XmlAnyAttributeAttribute | 指定成员(返回XmlAttribute对象的数组的字段)可以包含XML属性 |
XmlAnyElementAttribute | 指定成员可以包含对象,该对象表示在序列化或反序列化的对象中没有相应成员的所有XML元素 |
XmlAnyElementAttributes | 表示XmlAnyElementAttribute对象的集合 |
XmlAttributeEventArgs | 为UnKnowAttribute提供数据 |
XmlAttributeOverrides | 允许你在使用XmlSerializer序列化或反序列化时重写属性、字段和类特性 |
XmlElementEventArgs | 为UnknownElement事件提供数据 |
XmlNamespaceDeclarationsAttribute | 指定目标属性、参数、返回值或类成员包含与XML文档中所用命名空间关联的前缀 |
XmlNodeEventArgs | 为UnknownNode时间提供数据 |
XmlSerializer | 将对象序列化到XML文档中和从XML文档中反序列化对象,XmlSerializer使你得以控制如何将对象编码到XML中 |
XmlSerializerNamespaces | 包含XmlSerializer用于在XML文档实例中生成限定名的XML命名空间和前缀 |
XmlTypeMapping | 包含从一种类型到另一种类型的映射 |
如:
[Serializable] public class Person { public Person() { } public int Id { get; set; } public string Name { get; set; } [XmlAttribute(DataType = "string")] public string Content { get; set; } [XmlIgnore] public int Age { get; set; } [XmlArray] [XmlArrayItem("Int32", typeof(Int32))] public IList ListInt { get; set; } }
XmlIgnore与NonSerialized的区别:
1、XmlIgnore能作用于属性,NonSerialized只作用于字段。
2、XmlIgnore对序列化与反序列化均有效,而NonSerialized只影响序列化,反序列化不管。(非百分百确定)