如何序列化一个列表< T>转换成XML? [英] How to serialize a List<T> into XML?

查看:169
本文介绍了如何序列化一个列表< T>转换成XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何转换列表:

 名单,其中,INT>分行=新的名单,其中,INT>();
Branches.Add(1);
Branches.Add(2);
Branches.Add(3);
 

这个XML:

 <分行>
    <分支ID =1/>
    <分支ID =2/>
    <分支ID =3/>
< /分行>
 

解决方案

您可以试试这个使用LINQ:

 名单,其中,INT>分行=新的名单,其中,INT>();
Branches.Add(1);
Branches.Add(2);
Branches.Add(3);

的XElement xmlElements =新的XElement(分行,Branches.Select(I =>新建的XElement(分支,I)));
System.Console.Write(xmlElements);
System.Console.Read();
 

输出:

 <分行>
  <分公司> 1< /支>
  <分公司> 2'; /支>
  <分公司>第3版; /支>
< /分行>
 

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

编辑:

的XElement xmlElements =新的XElement(分行,Branches.Select(I =>新建的XElement(分支,新XAttribute(ID,I))));

输出:

 <分行>
  <分支ID =1/>
  <分支ID =2/>
  <分支ID =3/>
< /分行>
 

How to convert this list:

List<int> Branches = new List<int>();
Branches.Add(1);
Branches.Add(2);
Branches.Add(3);

into this XML:

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

解决方案

You can try this using 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();

Output:

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

Forgot to mention: you need to include using System.Xml.Linq; namespace.

EDIT:

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

output:

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

这篇关于如何序列化一个列表&LT; T&GT;转换成XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆