【发布时间】:2020-01-08 19:41:38
【问题描述】:
我正在尝试在 XDocument 中保存带有嵌套列表的对象列表。那么如何实现呢?
我有一堂课:
public class Book
{
public string Id { get; }
public string Title { get; set; }
public string Isbn { get; set; }
public List<string> Authors { get; set; }
public int Pages { get; set; }
...
}
还有一个类来存储它:
public class FileBookStore : IEntryStore<Book>
{
private List<Book> loadedBooks;
private string filename;
...
private static async Task<IEnumerable<Book>> ReadDataAsync(string filename)
{
...
IEnumerable<Book> result = XDocument.Parse(text)
.Root
.Elements("book")
.Select(e =>
new Book
{
Title = e.Attribute("title").Value,
Isbn = e.Attribute("isbn").Value,
Authors = new List<string>() //and here
});
return result;
}
static async Task SaveDataAsync(string filename, IEnumerable<Book> books)
{
XDocument root = new XDocument(
new XElement("catalog",
books.Select(n =>
new XElement("book",
new XAttribute("title", n.Title ?? ""),
new XAttribute("isbn", n.Isbn ?? ""),
//stuck in a line below
new XElement("authors", books.Select(n => new XElement("author"), new XAttribute("name"))),
new XAttribute("pages", n.Pages),
new XAttribute("year", n.Year),
new XAttribute("publisher", n.Publisher ?? "")))));
using (StreamWriter writer = new StreamWriter(filename))
{
await writer.WriteAsync(root.ToString()).ConfigureAwait(false);
}
}
我对这部分完全感兴趣。如何在集合中保存和加载对象?
【问题讨论】:
标签: c# linq linq-to-xml