如何转换此列表:
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>
答案 0 :(得分:27)
您可以使用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>
答案 1 :(得分:7)
您可以使用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 Serialization。
[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());
}