C#的XML序列化和反序列化1
3.1 从可串行化的类中定制XML串行化
1.格式化XML文档元素
[XmlRoot(ElementName = " Pupil " , Namespace = " urn:MyNamespace " )]
public class Student

{
// 则生成XML文档中,根元素<Pupil xmlns="urn:MyNamespace">
}
2.格式化XML元素
[XmlElement(ElementName = " FullName " , Namespace = " urn:OtherNamespace " )]
public string Name

{

get
{ return name; }

set
{ name = value; }
}
生成XML如下:
<? xml version = " 1.0 " encoding = " utf-8 " ?>
< Pupil xmlns:xsd = " http://www.w3.org/2001/XMLSchema "
xmlns:d1p1 = " urn:OtherNamespace " >
< d1p1:FullName > Thomas Smith </ d1p1:FullName >
</ Pupil >
这里的d1p1是自动生成的,在标题4,有办法自己指定Namespace前缀。
3.格式化XML属性
[XmlAttribute(AttributeName = " StudentNumber " , Namespace = " urn:MyNamespace " )]
public string Name

{

get
{ return name; }

set
{ name = value; }
}
同样还是Name属性,这次是使用XmlAttribute标签,生成XML如下:
<? xml version = " 1.0 " encoding = " utf-8 " ?>
< Pupil xmlns:xsd = " http://www.w3.org/2001/XMLSchema "
xmlns:d1p1 = " urn:OtherNamespace "
d1p1:Name = " Thomas Smith " >
</ Pupil >
XML属性在空间利用率上比XML元素略高一些。
4.为元素/属性设计限定的命名空间
使用XmlSerializer的Serialize方法重载,额外带一个XmlSerializerNamespace参数,指定这个命名空间前缀
public void SerializeIt( string filename)

{
// 自定义命名空间
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add( " xsd " , " http://www.w3.org/2001/XMLSchema " );
ns.Add( " xsi " , " http://www.w3.org/2001/XMLSchema-instance " );
ns.Add( " otherNS " , " urn:OtherNamespace " );

XmlSerializer serializer = new XmlSerializer( typeof (Book));
StreamWriter writer = new StreamWriter(filename);
Book myBook = new Book();

// 使用Serialize重载方法
serializer.Serialize(writer, myBook, ns);
writer.Close();
}
从而生成完全自定义的XML:
<? xml version = " 1.0 " encoding = " utf-8 " ?>
< Pupil xmlns:xsd = " http://www.w3.org/2001/XMLSchema "
xmlns:otherNS = " urn:OtherNamespace "
xmlns:xsi = " http://www.w3.org/2001/XMLSchema-instance "
otherNS:StudentNumber = " 8007 " xmlns = " urn:MyNamespace " >
< otherNS:FullName > Thomas Smith </ otherNS:FullName >
</ Pupil >