以下為將被序列化的類Entity: [XmlRoot("Root")] public class Entity { [XmlAttribute(AttributeName = "Attr1")] public string Attribute1; [XmlElement("SecondLevel") ...
以下為將被序列化的類Entity:
[XmlRoot("Root")]
public class Entity
{
[XmlAttribute(AttributeName = "Attr1")]
public string Attribute1;
[XmlElement("SecondLevel")]
public SecondLevel SecondLevel;
public override string ToString()
{
return Serializer.Serialize(this);
}
}
public class SecondLevel
{
[XmlElement("ThirdLevel")]
public List<ThirdLevel> ThirdLevel;
}
public class ThirdLevel
{
[XmlAttribute(AttributeName = "Attribute1")]
public string Attribute1;
[XmlAttribute(AttributeName = "Attribute2")]
public string Attribute2;
[XmlElement("Ele1")]
public Element Ele1;
}
public class Element
{
[XmlAttribute(AttributeName = "Attr1")]
public string Attribute1;
[XmlText]
public string Value;
}
以下為Entity類一實例序列化後的xml文件:
<?xml version="1.0"?>
<Root Attr1="attribute1">
<SecondLevel>
<ThirdLevel Attribute1="at1" Attribute2="at2">
<Ele1 Attr1="at1">v</Ele1>
</ThirdLevel>
<ThirdLevel Attribute1="att1" Attribute2="att2">
<Ele1 Attr1="att1">va</Ele1>
</ThirdLevel>
<ThirdLevel Attribute1="attr1" Attribute2="attr2">
<Ele1 Attr1="attr1">val</Ele1>
</ThirdLevel>
</SecondLevel>
</Root>
值得一提的是,在實際運用中,自定義命名空間[xmlns:......]的方法是使用XmlSerializer類的重載方法:
public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces);
進行序列化,其中“namespaces”參數可由以下代碼創建:
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(
new[] { new XmlQualifiedName(string.Empty, "") });