码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2018-07-31 00:39:19      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:empty   obj   特性   void   turn   tostring   lis   xml序列化   ret   

 

以下为将被序列化的类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, "") });

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

标签:empty   obj   特性   void   turn   tostring   lis   xml序列化   ret   

原文地址:https://www.cnblogs.com/xuanhu/p/9393534.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!