c# – 如何将列表序列化为XML?

如何转换此列表:
List<int> Branches = new List<int>();
Branches.Add(1);
Branches.Add(2);
Branches.Add(3);

进入这个XML:

<Branches>
    <branch id="1" />
    <branch id="2" />
    <branch id="3" />
</Branches>

解决方法

你可以尝试使用LINQ:
List<int> Branches = new List<int>();
Branches.Add(1);
Branches.Add(2);
Branches.Add(3);

XElement xmlElements = new XElement("Branches",Branches.Select(i => new XElement("branch",i)));
System.Console.Write(xmlElements);
System.Console.Read();

输出

<Branches>
  <branch>1</branch>
  <branch>2</branch>
  <branch>3</branch>
</Branches>

忘了提一下:你需要包括使用System.Xml.Linq;命名空间.

编辑:

XElement xmlElements = new XElement(“Branches”,Branches.Select(i => new XElement(“branch”,new XAttribute(“id”,i))));

输出

<Branches>
  <branch id="1" />
  <branch id="2" />
  <branch id="3" />
</Branches>

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...