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>
4

2 回答 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>
于 2013-06-11T12:11:55.647 回答
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());
}
于 2013-06-11T12:33:56.107 回答