c# - XElement 和列表<T>

标签 c# .net linq-to-xml xelement

我有一个具有以下属性的类:

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/

相关文章:

c# - 使用Nest 6.x将30d转换为两倍

c# - 无法使 ShouldSerialize 模式与 XmlSerializer 一起使用

c# - 如何获取父节点且只有一个子节点

c# - 在 C# 中解析 XML 字符串

c# - 使用正则表达式解析文本文件

c# - 避免使用 DataContractSerializer 和继承重复自己 (DRY)

c# - asp.net core 中的 jwt token 无效

c# - 对象属性的反射(reflect)

c# - ASP.NET 将 PDF 写入文件系统

c# - 异常 : The XPath expression evaluated to unexpected type System. Xml.Linq.XAttribute