[英]XDocument reading child elements
我剛剛開始在C#中使用Linq to XML。 我有一個包含有關書籍信息的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類,等等。
如果要按ID
搜索:
var author = document.Descendans("book")
.Where(x => (string)x.Attribute("id") == id)
.Select(x => (string)x.Element("author"))
.FirstOrDefault();
如果Title
搜索:
var author = document.Descendans("book")
.Where(x => (string)x.Element("title") == title)
.Select(x => (string)x.Element("author"))
.FirstOrDefault();
然后檢查是否為空並返回作者名稱:
if(author != null)
return author;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.