3.1 從可串行化的類中定製XML串行化
1.格式化XML文檔元素
public class Student
{
// 則生成XML文檔中,根元素<Pupil xmlns="urn:MyNamespace">
}
2.格式化XML元素
public string Name
{
get { return name; }
set { name = value; }
}
生成XML如下:
< 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屬性
public string Name
{
get { return name; }
set { name = value; }
}
同樣還是Name屬性,這次是使用XmlAttribute標籤,生成XML如下:
< Pupil xmlns:xsd = " http://www.w3.org/2001/XMLSchema "
xmlns:d1p1 = " urn:OtherNamespace "
d1p1:Name = " Thomas Smith " >
</ Pupil >
XML屬性在空間利用率上比XML元素略高一些。
4.爲元素/屬性設計限定的命名空間
使用XmlSerializer的Serialize方法重載,額外帶一個XmlSerializerNamespace參數,指定這個命名空間前綴
{
// 自定義命名空間
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:
< 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 >