gpt4 book ai didi

c# - XDocument 读取子元素

转载 作者:太空宇宙 更新时间:2023-11-03 19:09:36 25 4
gpt4 key购买 nike

我刚刚开始将 Linq to XML 与 C# 结合使用。我有一个包含书籍信息的 XML 文件。

XML 文件具有以下结构:

<?xml version="1.0"?>
<catalog>
<book id="bk112">
<author>Galos, Mike</author>
<title>Visual Studio 7: A Comprehensive Guide</title>
<genre>Computer</genre>
<price>49.95</price>
<publish_date>2001-04-16</publish_date>
<description>Microsoft Visual Studio 7 is explored in depth,
looking at how Visual Basic, Visual C++, C#, and ASP+ are
integrated into a comprehensive development
environment.</description>
</book>
</catalog>

我已经设法编写代码,让我从 XML 文件中获取作者列表和书籍列表:

public List<string> GetBooks()
{
XDocument document = XDocument.Load(XMLFileLocation);

var query = from t in document.Descendants("title")
select t.Value;

return query.ToList<string>();
}

但是,我不知道如何继续制作一种方法来获取有关特定书籍的信息。例如:

GetBookAuthor("MyBook");

我该怎么做?

最佳答案

如果您想坚持使用 XDocument,这是一种通过书名获取作者的简单方法:

public static string GetBookAuthor(XDocument xDoc, string title)
{
return xDoc.Root
.Elements("book")
.First(b => b.Element("title").Value == title)
.Element("author")
.Value;
}

但是我建议使用面向对象的方法:

为什么不创建一个带有 Author 和 Title 属性的 Book 类,那么您就不需要 GetBookAuthor 方法了?

public class Book
{
public string Title { get; set; }
public string Author { get; set; }
// other Book properties ...
}

获取 Book 对象的列表:

public static List<Book> GetBooks()
{
XDocument document = XDocument.Load(xmlFile);

var query = from t in document.Root.Elements("book")
select new Book()
{
Author = t.Element("author").Value,
Title = t.Element("title").Value
};

return query.ToList();
}

然后您可以按名称返回 Book 对象:

public static Book GetBook(List<Book> bookList, string title)
{
return bookList.First(b => b.Title == title);
}

并访问 Author 属性:

var bookList = GetBooks()
var author = GetBook(bookList, "MyBook").Author;

现在,如果 author 是更复杂的元素,您也可以创建一个 Author 类等。

关于c# - XDocument 读取子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21922334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com