微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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>

原文地址:https://www.jb51.cc/csharp/93800.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐