您的位置:首页 > 其它

设计用于浅串行化的类

2008-08-12 00:29 141 查看
3.1 从可串行化的类中定制XML串行化

1.格式化XML文档元素

[XmlRoot(ElementName = "Pupil", Namespace = "urn:MyNamespace")]

public class Student

[XmlElement(ElementName = "FullName", Namespace = "urn:OtherNamespace")]

public string Name

<?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

<?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 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

[XmlElement(DataType="date")]

public DateTime EnrollDate

public enum Color

private Color showColor;

public Color ShowColor

[XmlArray(ElementName="Cources"),

XmlArrayItem(Type=typeof(String), ElementName="CourceName"),

XmlArrayItem(Type=typeof(Int32), ElementName="CourceCode")]

public Object[] Subjects

<Cources>

<CourceName>Physics</CourceName>

<CourceCode>123</CourceCode>

<CourceName>IT</CourceName>

</Cources>

9.定义可空的对象引用

如果某属性为null,在串行化时会忽略该属性,可以显示替代的信息,方法如下:

[XmlElement(IsNullable = true)]

public string Address

public void MySerialize(Student obj, string filename)

{

SoapReflectionImporter importer = new SoapReflectionImporter();

XmlTypeMapping mapping = importer.ImportMembersMapping(typeof(Student));

XmlTextWriter writer = new XmlTextWriter(filename, System.Text.Encoding.UTF8);

writer.WriteStartElement("MyWrapperElement");

writer.WriteAttributeString("xmlns", "xsd", Nothing, "http://www.w3.org/2001/XMLSchema");

writer.WriteAttributeString("xmlns", "xsi", Nothing, "http://www.w3.org/2001/XMLSchema-instance");

writer.WriteAttributeString("xmlns", "soap", Nothing, "http://schemas.xmlsoap.org/soap/encoding/");

writer.WriteAttributeString("xmlns", "otherNS", Nothing, "urn:OtherNamespace");

XmlSerializer serializer = new XmlSerializer(mapping);

serializer.Serialize(writer, obj);

writer.WriteEndElement();

writer.Close();

}
于是,生产SOAP格式的XML文件。

Soap编码串行化的属性,无XMLText和XMLArray,其它的对应如下:

SoapTypeXmlType
SoapElementXmlElement
SoapAttributeXmlAttribute
SoapEnumXmlEnum
SoapIgnoreXmlIgnore
SoapIncludeXmlInclude
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: