Jag*_*agd 8 .net c# xelement linq-to-xml
我有一个具有以下属性的类:
public class Author {
public string FirstName { get; set; }
public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
接下来,我有一个像这样的作者列表:
List<Author> authors = new List<Author> ();
authors.add(
new Author {
FirstName = "Steven",
LastName = "King"
});
authors.add(
new Author {
FirstName = "Homer",
LastName = ""
});
Run Code Online (Sandbox Code Playgroud)
现在,我正在尝试使用Linq to XML来生成表示我的作者列表的XML.
new XElement("Authors",
new XElement("Author",
from na in this.Authors
select new XElement("First", na.First)))
Run Code Online (Sandbox Code Playgroud)
上面的块不会像我期望的那样生成XML.我得到的是:
<Authors>
<Author>
<First>Steven</First>
<First>Homer</First>
</Author>
<Authors>
Run Code Online (Sandbox Code Playgroud)
我希望XML输出看起来像是:
<Authors>
<Author>
<First>Steven</First>
<Last>King</Last>
</Author>
<Author>
<First>Homer</First>
<Last></Last>
</Author>
</Authors>
Run Code Online (Sandbox Code Playgroud)
任何有关如何让XML看起来像我需要它的帮助将非常感激!
cas*_*One 11
您需要将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)));
Run Code Online (Sandbox Code Playgroud)
这将为您提供所需的结果.