Linq To Xml
关于Linq的简介请看这篇文章:查询表达式(LINQ)简介
本文简要介绍通过Linq操作XML文件
1.准备一个XML文件
本例的XML文件内容主要是书籍信息,代码如下:
<?xml version="1.0" encoding="utf-8" ?> <Books> <Category Order="1" Name="文学类"> <Book Order="1" Name="战争与和平" Author="张三" Price="120.00" Publish="北京大学出版社"></Book> <Book Order="2" Name="简爱" Author="李四" Price="153.00" Publish="清华大学出版社"></Book> <Book Order="3" Name="罪与罪" Author="王五" Price="89.00" Publish="工业出版社"></Book> </Category> <Category Order="3" Name="计算机类"> <Book Order="1" Name="Linq高级编程" Author="童贝" Price="67.40" Publish="北京大学出版社"></Book> <Book Order="2" Name="深入浅出WPF" Author="向刚" Price="65.00" Publish="清华大学出版社"></Book> <Book Order="3" Name="ASP.Net MVC4" Author="马六" Price="89.00" Publish="工业出版社"></Book> </Category> <Category Order="2" Name="科技类"> <Book Order="1" Name="自然" Author="邵叶" Price="130.40" Publish="北京大学出版社"></Book> <Book Order="2" Name="新工业革命" Author="李安" Price="65.00" Publish="清华大学出版社"></Book> <Book Order="3" Name="时空" Author="马六" Price="150.00" Publish="工业出版社"></Book> </Category> </Books>
2.编写Book类
创建一个Book类
public class Book { /// <summary> /// 分类名称 /// </summary> public string Category { get; set; } /// <summary> /// 书籍名称 /// </summary> public string Name { get; set; } /// <summary> /// 价格 /// </summary> public string Price { get; set; } /// <summary> /// 作者 /// </summary> public string Author { get; set; } /// <summary> /// 出版社 /// </summary> public string Publish { get; set; } }
3.通过Linq操作XML文件
先引入命名空间
using System.Xml.Linq;
操作XML文件的代码主要如下:
private void LoadXml() { XElement bookXml = XElement.Load(Server.MapPath("~/Book.xml")); if (bookXml == null) { return; } // 查找所有书籍分类 var categorysElement = from item in bookXml.Elements("Category") orderby (int.Parse(item.Attribute("Order").Value)) select item; List<Book> listBook = new List<Book>(); foreach (var categoryElement in categorysElement) { // 获取书籍分类的名称 string categoryName = categoryElement.Attribute("Name").Value; // 查找此分类下的所有书籍 var booksElement = from book in categoryElement.Elements("Book") orderby (int.Parse(book.Attribute("Order").Value)) select book; foreach (var bookElement in booksElement) { Book book = new Book(); book.Category = categoryName; book.Name = bookElement.Attribute("Name").Value; book.Author = bookElement.Attribute("Author").Value; book.Price = bookElement.Attribute("Price").Value; book.Publish = bookElement.Attribute("Publish").Value; listBook.Add(book); } } this.grdBooks.DataSource = listBook; this.grdBooks.DataBind(); }
结果如下图所示:
代码下载:LinqToXml