数组的Xml序列化需要使用XmlArrayAttribute和XmlArrayItemAttribute;XmlArrayAttribute指定数组元素的Xml节点名,XmlArrayItemAttribute指定数组元素的Xml节点名。
如下代码示例:
/
*玉开技术博客 http://www.111com.net */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;namespace UseXmlSerialization
{
class Program
{
static void Main(string[] args)
{
//声明一个猫咪对象
var cWhite = new Cat { Color = "White", Speed = 10, Saying = "White or black, so long as the cat can catch mice, it is a good cat" };
var cBlack = new Cat { Color = "Black", Speed = 10, Saying = "White or black, so long as the cat can catch mice, it is a good cat" };CatCollection cc = new CatCollection { Cats = new Cat[] { cWhite,cBlack} };
//序列化这个对象
XmlSerializer serializer = new XmlSerializer(typeof(CatCollection));//将对象序列化输出到控制台
serializer.Serialize(Console.Out, cc);Console.Read();
}
}[XmlRoot("cats")]
public class CatCollection
{
[XmlArray("items"),XmlArrayItem("item")]
public Cat[] Cats { get; set; }
}[XmlRoot("cat")]
public class Cat
{
//定义Color属性的序列化为cat节点的属性
[XmlAttribute("color")]
public string Color { get; set; }//要求不序列化Speed属性
[XmlIgnore]
public int Speed { get; set; }//设置Saying属性序列化为Xml子元素
[XmlElement("saying")]
public string Saying { get; set; }
}
}
以上代码将输出:
White or black, so long as the cat can catch mice, it is a good
cat
White or black, so long as the cat can catch mice, it is a good
cat
创造与魔法 安卓版v1.0.0750
创造与魔法是一款开放世界手游,在游戏中玩家可探索这个奇妙的世
创造与魔法修改版 最新版v1.0.0750
创造与魔法无限点券版是款探索冒险游戏,该款游戏的操作还是蛮自
战争与文明官方版本 安卓版v1.7.16
战争与文明是一款由上海邮通科技有限公司开发的战争策略游戏,这
迷你世界0元领皮肤无限迷你币版 最新安卓版v1.43.0
迷你世界0元购买皮肤版是这款开放沙盒冒险建造游戏的特殊破解版
创造与魔法无限经验版 安卓版v1.0.0750
创造与魔法无限经验版是款可以改造环境,整个游戏的自由度还是蛮