您可以通过两种解决方案获取 XML 字符串。
解决方案 1:要获取 XML 字符串,您需要将 XmlElement 放在 XDocument 对象中。尝试,
List<Peoples> peopleList = new List<Peoples>();
peopleList.Add(new Peoples() { Name = "xxx", Age = 23 });
peopleList.Add(new Peoples() { Name = "yyy", Age = 25 });
var people = (from item in peopleList
select new XElement("people",
new XElement("name", item.Name),
new XElement("age", item.Age)
));
XElement root = new XElement("Peoples");
root.Add(people);
XDocument xDoc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
root);
string str = xDoc.ToString();
您需要根元素来获取 Xml 字符串。
输出:
<Peoples>
<people>
<name>xxx</name>
<age>23</age>
</people>
<people>
<name>yyy</name>
<age>25</age>
</people>
</Peoples>
这里将姓名和年龄视为 XElement。正如您提到的有问题的代码XAttribute
。如果您想将姓名和年龄视为XAttribute
.
List<Peoples> peopleList = new List<Peoples>();
peopleList.Add(new Peoples() { Name = "xxx", Age = 23 });
peopleList.Add(new Peoples() { Name = "yyy", Age = 25 });
var people = (from item in peopleList
select new XElement("people",
new XAttribute("name", item.Name),
new XAttribute("age", item.Age)
));
XElement root = new XElement("Peoples");
root.Add(people);
XDocument xDoc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
root);
string str = xDoc.ToString();
输出:
<Peoples>
<people name="xxx" age="23" />
<people name="yyy" age="25" />
</Peoples>
解决方案 2:如果您想要来自以下的 Xml 字符串,请尝试以下操作List<XElement>
:
string str = people.Select(x => x.ToString()).Aggregate(String.Concat);
如果 XElement 用于姓名和年龄,则输出:
<people>
<name>xxx</name>
<age>23</age>
</people>
<people>
<name>yyy</name>
<age>25</age>
</people>
如果 XAttribute 用于姓名和年龄,则输出:
<people name="xxx" age="23" />
<people name="yyy" age="25" />
希望它应该工作。解决方案 2 最适合您的需要。