LINQ to XML 是一个在.NET Framework中的组件,它允许您使用LINQ(Language Integrated Query)查询和操作XML文档。它使用一种更直观的方式来处理XML,可以方便地创建、查询和修改XML文档。
准备一个data.xml 文件
XML<Books>
<Book>
<Title>The Catcher in the Rye</Title>
<Author>J.D. Salinger</Author>
<Price>15.99</Price>
</Book>
<Book>
<Title>To Kill a Mockingbird</Title>
<Author>Harper Lee</Author>
<Price>12.49</Price>
</Book>
<Book>
<Title>1984</Title>
<Author>George Orwell</Author>
<Price>19.95</Price>
</Book>
<Book>
<Title>The Great Gatsby</Title>
<Author>F. Scott Fitzgerald</Author>
<Price>10.79</Price>
</Book>
<Book>
<Title>Pride and Prejudice</Title>
<Author>Jane Austen</Author>
<Price>8.99</Price>
</Book>
<Book>
<Title>Brave New World</Title>
<Author>Aldous Huxley</Author>
<Price>14.25</Price>
</Book>
<Book>
<Title>The Hobbit</Title>
<Author>J.R.R. Tolkien</Author>
<Price>17.50</Price>
</Book>
<Book>
<Title>Harry Potter and the Sorcerer's Stone</Title>
<Author>J.K. Rowling</Author>
<Price>22.99</Price>
</Book>
<Book>
<Title>Fahrenheit 451</Title>
<Author>Ray Bradbury</Author>
<Price>11.15</Price>
</Book>
<Book>
<Title>The Lord of the Rings</Title>
<Author>J.R.R. Tolkien</Author>
<Price>29.99</Price>
</Book>
</Books>
当使用LINQ to XML中的Descendants
方法时,您可以通过这个方法获取指定元素名称的所有后代元素。
C#private void btnSearch_Click(object sender, EventArgs e)
{
// 加载XML文档
XDocument doc = XDocument.Load("./data.xml");
// 使用LINQ查询从XML文档中获取特定元素
var books = from book in doc.Descendants("Book")
where (decimal)book.Element("Price") > 15
select new
{
Title = book.Element("Title").Value,
Author = book.Element("Author").Value,
Price = (decimal)book.Element("Price")
};
foreach (var book in books)
{
lstMain.Items.Add($"{book.Title} by {book.Author}, Price: ${book.Price}");
}
}
使用LINQ to XML,您可以轻松地查询具有特定属性的元素。
我们给Book 添加属性
C#private void btnSearchByProperty_Click(object sender, EventArgs e)
{
// 加载XML文档
XDocument doc = XDocument.Load("./data.xml");
// 查询具有特定ISBN属性的Book元素
var books = from book in doc.Descendants("Book")
where book.Attribute("ISBN")?.Value == "978-0-13-217229-3"
select book;
foreach (var book in books)
{
lstMain.Items.Add($"{book.Element("Title").Value} by {book.Element("Author").Value}, Price: ${book.Element("Price").Value}");
}
}
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!