通过XMLSerializer,可以很方便的Serialize/Deserialize Object/XML。
1.可以实现在Class, 而非Interface
2.仅在对象的Public Field/ Property {支持get, set}上使用
3.可以使用一些Useful Tool来自动产生CS Class和XML文件对应关系,包括:
- Top XML has an excellent article on the
XmlSerializer
. - Skeleton Crew is a tool to help build XML serializable code from XML samples.
- Sells Brothers XML Pre-Compiler is a good tool for testing the serializability of a class or model that can tell you why a class isn't serializable.
有用的属性Attribute如下:
1)XmlRootAttribute
类名可以和XML Root Element不同
namespace XmlEntities {
[XmlRoot("XmlDocRoot")]
public class RootClass {
}
}
<XmlDocRoot />2)XmlElementAttribute
允许类成员作为XML的Element,对于复杂的Element(包括Field.Property),可以构造复杂对象。
[XmlRoot("XmlDocRoot")]
public class RootClass {
private string element_description;
[XmlElement("Description")]
public string Description {
get { return element_description; }
set { element_description = value; } }<XmlDocRoot>
<Description>text</Description>
</XmlDocRoot>3)XmlAttributeAttribute
允许类成员作为XML的Attribute,仅支持简单数据(包括一个Attribute)。对于>2个Attribute,需要复杂对象来实现。
[XmlRoot("XmlDocRoot")]
public class RootClass {
private int attribute_id;
[XmlAttribute("id")]
public int Id {
get { return attribute_id; }
set { attribute_id = value; }
}
}<XmlDocRoot id="1" />
4)XmlIgnoreAttribute如果对于Public Field/Property,如果不想和XML对应,可以排除。
[XmlRoot("XmlDocRoot")]
public class RootClass {
private System.IO.Stream stream;
[XmlIgnore()]
public System.IO.Stream Stream {
get { return stream; }
set { stream = value; }
}
}5)XmlArrayAttribute & XmlArrayItemAttribute
数组序列化支持。XmlArrayAttribute:ParmentElement; XmlArrayItemAttribute:Element Collection。
XmlRoot("XmlDocRoot")]
public class RootClass {
private string[] element_list;
[XmlArrayItem("ListItem", typeof(string))]
[XmlArray("List")]
public string[] List {
get { return element_list; }
set { element_list = value; }
}
}<XmlDocRoot>
<List>
<ListItem>string</ListItem>
<ListItem>string</ListItem>
</List>
</XmlDocRoot>Sample Code:
XmlSerializer serializer = new XmlSerializer(typeof(RootClass));
RootClass result = (RootClass)serializer.Deserialize(new System.Xml.XmlTextReader(path));