如何序列化一个列表&LT; T&GT;转换成XML? [英] How to serialize a List<T> into XML?
本文介绍了如何序列化一个列表&LT; T&GT;转换成XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何转换列表:
名单,其中,INT&GT;分行=新的名单,其中,INT&GT;();
Branches.Add(1);
Branches.Add(2);
Branches.Add(3);
这个XML:
&LT;分行&GT;
&LT;分支ID =1/&GT;
&LT;分支ID =2/&GT;
&LT;分支ID =3/&GT;
&LT; /分行&GT;
解决方案
您可以试试这个使用LINQ:
名单,其中,INT&GT;分行=新的名单,其中,INT&GT;();
Branches.Add(1);
Branches.Add(2);
Branches.Add(3);
的XElement xmlElements =新的XElement(分行,Branches.Select(I =&gt;新建的XElement(分支,I)));
System.Console.Write(xmlElements);
System.Console.Read();
输出:
&LT;分行&GT;
&LT;分公司&GT; 1&LT; /支&GT;
&LT;分公司&GT; 2'; /支&GT;
&LT;分公司&GT;第3版; /支&GT;
&LT; /分行&GT;
忘了提:你需要包括使用System.Xml.Linq的;
命名空间
编辑:
的XElement xmlElements =新的XElement(分行,Branches.Select(I =&gt;新建的XElement(分支,新XAttribute(ID,I))));
输出:
&LT;分行&GT;
&LT;分支ID =1/&GT;
&LT;分支ID =2/&GT;
&LT;分支ID =3/&GT;
&LT; /分行&GT;
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屋!
查看全文