C# 如何将 List<T> 序列化为 XML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17043663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:26:44  来源:igfitidea点击:

How to serialize a List<T> into XML?

c#.netxml

提问by Ujjwal27

How to convert this list:

如何转换此列表:

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

into this XML:

进入这个 XML:

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

采纳答案by Praveen

You can try this using LINQ:

您可以使用 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.

忘了提:你需要包含using System.Xml.Linq;命名空间。

EDIT:

编辑:

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

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>

回答by Dustin Kingen

You can use Linq-to-XML

您可以使用Linq-to-XML

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

var branchesXml = Branches.Select(i => new XElement("branch",
                                                    new XAttribute("id", i)));
var bodyXml = new XElement("Branches", branchesXml);
System.Console.Write(bodyXml);

Or create the appropriate class structure and use XML Serialization.

或者创建适当的类结构并使用XML 序列化

[XmlType(Name = "branch")]
public class Branch
{
    [XmlAttribute(Name = "id")]
    public int Id { get; set; }
}

var branches = new List<Branch>();
branches.Add(new Branch { Id = 1 });
branches.Add(new Branch { Id = 2 });
branches.Add(new Branch { Id = 3 });

// Define the root element to avoid ArrayOfBranch
var serializer = new XmlSerializer(typeof(List<Branch>),
                                   new XmlRootAttribute("Branches"));
using(var stream = new StringWriter())
{
    serializer.Serialize(stream, branches);
    System.Console.Write(stream.ToString());
}