我有一个具有以下属性的类:
public class Author {
public string FirstName { get; set; }
public string LastName { get; set; }
}
接下来,我有一个这样的作者列表:
List<Author> authors = new List<Author> ();
authors.add(
new Author {
FirstName = "Steven",
LastName = "King"
});
authors.add(
new Author {
FirstName = "Homer",
LastName = ""
});
现在,我正在尝试使用 Linq to XML 来生成代表我的作者列表的 XML。
new XElement("Authors",
new XElement("Author",
from na in this.Authors
select new XElement("First", na.First)))
上面的 block 没有像我期望的那样生成 XML。我得到的是:
<Authors>
<Author>
<First>Steven</First>
<First>Homer</First>
</Author>
<Authors>
我希望 XML 输出看起来像:
<Authors>
<Author>
<First>Steven</First>
<Last>King</Last>
</Author>
<Author>
<First>Homer</First>
<Last></Last>
</Author>
</Authors>
如能提供有关如何使 XML 看起来符合我需要的任何帮助,我们将不胜感激!
最佳答案
您需要通过 IEnumerable<XElement>
作为第二个参数查询,而不是“作者”字符串,如下所示:
// Note the new way to initialize collections in C# 3.0.
List<Author> authors = new List<Author> ()
{
new Author { FirstName = "Steven", LastName = "King" }),
new Author { FirstName = "Homer", LastName = "" })
};
// The XML
XElement xml = new XElement("Authors",
from na in this.Authors
select new XElement("Author",
new XElement("First", na.FirstName),
new XElement("Last", na.LastName)));
这将为您提供所需的结果。
关于c# - XElement 和列表<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1127385/