3.1 从可串行化的类中定制XML串行化
1.格式化XML文档元素
[XmlRoot(ElementName = "Pupil", Namespace = "urn:MyNamespace")]
public class Student
}
2.格式化XML元素
[XmlElement(ElementName = "FullName", Namespace = "urn:OtherNamespace")]
public string Name
}
生成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
}
同样还是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)
}
从而生成完全自定义的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>
5.格式化文本内容
[XmlText()]
public string Name
}
则Name会生成在<Pupil>XXX(Name)</Pupil>中作为文本
6.为元素/属性定义数据类型
XML Schema类型与.NET数据类型有一个Mapping,比如说type对应System.DateTime
[XmlElement(DataType="date")]
public DateTime EnrollDate
}
于是生成XML: <EnrollDate>2007-10-19</EnrollDate>
XMLRoot,XmlAttribute,XMLElement,XMLText,XMLArrayItem标签都可以指定DataType
7.为枚举修饰符指定其他名称
public enum Color
}
生成XML如下格式:
<ShowColor>White Color</ShowColor>
8.串行化多肽数组
[XmlArray(ElementName="Cources"),
XmlArrayItem(Type=typeof(String), ElementName="CourceName"),
XmlArrayItem(Type=typeof(Int32), ElementName="CourceCode")]
public Object[] Subjects
}
XmlArrayItem负责指定数组中可能出现的元素类型,以及该类型对应的XML前缀
比如说创建如下的数组:
Object obj = new Object["Physics", 123, "IT"];
生成XML如下格式:
<Cources>
<CourceName>Physics</CourceName>
<CourceCode>123</CourceCode>
<CourceName>IT</CourceName>
</Cources>
9.定义可空的对象引用
如果某属性为null,在串行化时会忽略该属性,可以显示替代的信息,方法如下:
[XmlElement(IsNullable = true)]
public string Address
}
在该位置,生成替代XML:
<Address xsi:nil="true" />
10.定义可忽略的字段/属性
[XmlIgnore()]
3.2 把XML串行化定制为SOAP编码格式
public void MySerialize(Student obj, string filename)
}
于是,生产SOAP格式的XML文件。
Soap编码串行化的属性,无XMLText和XMLArray,其它的对应如下:
| SoapType |
XmlType |
| SoapElement |
XmlElement |
| SoapAttribute |
XmlAttribute |
| SoapEnum |
XmlEnum |
| SoapIgnore |
XmlIgnore |
| SoapInclude |
XmlInclude |
相关文章: