欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# xml序列化与反序列化 特性的使用

程序员文章站 2022-04-28 09:48:19
以下为将被序列化的类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, "") });