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

20

如何将这个列表转换:

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>

2
从这里开始,然后带着具体的问题回来:http://msdn.microsoft.com/en-us/library/system.xml.serialization.aspx - Chris Searles
2个回答

32

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

忘记提到:您需要包括 using 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>

4
这不会输出<branch id="1" />,它会输出<branch>1</branch> - James
1
你是指 new XElement("branch", new XAttribute("id", i)) 吗? - lisp
@James,@lisp 谢谢你们的纠正。我已经更正了我的答案。 - Praveen

11
你可以使用 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);

或者创建适当的类结构并使用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());
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接