XElement和List< T> [英] XElement and List<T>
问题描述
我有一个具有以下属性的类:
I have a class that has the following properties:
public class Author {
public string FirstName { get; set; }
public string LastName { get; set; }
}
接下来,我有一个类似的作者列表:
Next, I have a List of Authors like so:
List<Author> authors = new List<Author> ();
authors.add(
new Author {
FirstName = "Steven",
LastName = "King"
});
authors.add(
new Author {
FirstName = "Homer",
LastName = ""
});
现在,我正在尝试使用Linq到XML,以便生成代表我的作者列表的XML.
Now, I am trying to use Linq to XML in order to generate the XML representing my Authors List.
new XElement("Authors",
new XElement("Author",
from na in this.Authors
select new XElement("First", na.First)))
上面的块没有生成XML,正如我期望的那样.我得到的是:
The block above does not generate the XML as I expect it to. What I get is:
<Authors>
<Author>
<First>Steven</First>
<First>Homer</First>
</Author>
<Authors>
我希望XML输出看起来是这样的:
What I want the XML output to look like is:
<Authors>
<Author>
<First>Steven</First>
<Last>King</Last>
</Author>
<Author>
<First>Homer</First>
<Last></Last>
</Author>
</Authors>
我们将非常感谢您提供有关如何使XML看起来像我需要的任何帮助!
Any help on how to get the XML to look as I need it to would be immensely appreciated!
推荐答案
You need to pass the IEnumerable<XElement>
query as the second parameter, not the "Author" string, like so:
// 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)));
这将为您提供所需的结果.
That will give you the result you need.
这篇关于XElement和List< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!