LINQ to XML实现XML文档的增删改查

1、实例中的XML文档(Books.xml) view plai co

<?xml version="1.0" encoding="utf-8"?>  
<bookstore>  
  <book id="1" category="CHILDREN">  
    <title>Harry Potter</title>  
    <author>J K. Rowling</author>  
    <publishDate>2005-08-15</publishDate>  
    <price>29.99</price>  
  </book>  
  <book id="2" category="WEB">  
    <title>Learning XML</title>  
    <author>Erik T. Ray</author>  
    <publishDate>2003-10-18</publishDate>  
    <price>39.95</price>  
  </book>  
  <book id="3" category="WEB">  
    <title>XQuery Kick Start</title>  
    <author>James McGovern</author>  
    <publishDate>2005-06-25</publishDate>  
    <price>49.99</price>  
  </book>  
</bookstore> 

2、 创建图书信息实体类(BookInfo.cs) view plain cop

/// <summary>  
/// 图书信息实体类  
/// </summary>  
public class BookInfo  
{  
    public int BookId { set; get; }             //图书ID  
    public string Title { set; get; }           //图书名称  
    public string Category { set; get; }        //图书分类  
    public string Author { set; get; }          //图书作者  
    public DateTime PublishDate { set; get; }   //出版时间  
    public Double Price { set; get; }           //销售价格  
}  

3、 创建图书信息业务逻辑类(BookInfoBLL.cs) view plain

using System.Linq;  
using System.Xml.Linq;  
public class BookInfoBLL  
{  
    private string _basePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"/xml/Books.xml";  //XML文件路径   
  
    /// <summary>  
    /// 创建图书XML文档(创建)  
    /// </summary>  
    public void CreateBookXml()  
    {   
        //获取图书列表  
        List<BookInfo> bookList = GetBookList();  
        //创建XML文档  
        XDocument bookDoc = new XDocument();  
        //创建声明对象  
        XDeclaration xDeclaration = new XDeclaration("1.0", "utf-8", "yes");  
        bookDoc.Declaration = xDeclaration;    //指定XML声明对象  
        //创建bookstore节点  
        XElement xElement = new XElement("bookstore");  
        foreach (BookInfo book in bookList)  
        {  
            //创建book节点  
            XElement bookXml = new XElement("book");  
            //添加属性  
            bookXml.Add(new XAttribute("id", book.BookId));  
            bookXml.Add(new XAttribute("category", book.Category));  
            //添加子节点  
            bookXml.Add(new XElement("title", book.Title));  
            bookXml.Add(new XElement("author", book.Author));  
            bookXml.Add(new XElement("publishDate", book.PublishDate.ToString("yyyy-MM-dd")));  
            bookXml.Add(new XElement("price", book.Price));  
            //将book节点添加到bookstore节点中  
            xElement.Add(bookXml);  
        }  
        //保存文件  
        bookDoc.Add(xElement);  
        bookDoc.Save(_basePath);  
    }  
  
    /// <summary>    
    /// 获取图书列表(查询)    
    /// </summary>    
    /// <param name="param">参数条件</param>    
    /// <returns>图书列表</returns>   
    public List<BookInfo> GetBookInfoList(BookInfo param)  
    {  
        List<BookInfo> bookList = new List<BookInfo>();  
        XElement xml = XElement.Load(_basePath);  
  
        var bookVar = xml.Descendants("book");   //默认查询所有图书  
        if (param.BookId != 0) //根据图书ID查询    
        {  
            bookVar = xml.Descendants("book").Where(a => a.Attribute("id").Value == param.BookId.ToString());  
        }    
        else if (!String.IsNullOrEmpty(param.Category)) //根据图书类别查询    
        {  
            bookVar = xml.Descendants("book").Where(a => a.Attribute("category").Value == param.Category);  
        }    
        else if (!String.IsNullOrEmpty(param.Title)) //根据图书名称查询    
        {  
            bookVar = xml.Descendants("book").Where(a => a.Element("title").Value == param.Title);  
        }  
  
        bookList = (from book in bookVar  
                    select new BookInfo  
                    {  
                        BookId = int.Parse(book.Attribute("id").Value),  
                        Category = book.Attribute("category").Value,  
                        Title = book.Element("title").Value,  
                        Author = book.Element("author").Value,  
                        PublishDate = DateTime.Parse(book.Element("publishDate").Value),  
                        Price = double.Parse(book.Element("price").Value)  
                    }).ToList();  
        return bookList;  
    }  
  
    /// <summary>    
    /// 增加图书信息(新增)    
    /// </summary>    
    /// <param name="param"></param>    
    /// <returns></returns>    
    public bool AddBookInfo(BookInfo param)  
    {  
        XElement xml = XElement.Load(_basePath);  
        //创建book节点  
        XElement bookXml = new XElement("book");  
        //添加属性  
        bookXml.Add(new XAttribute("id", param.BookId));  
        bookXml.Add(new XAttribute("category", param.Category));  
        //添加子节点  
        bookXml.Add(new XElement("title", param.Title));  
        bookXml.Add(new XElement("author", param.Author));  
        bookXml.Add(new XElement("publishDate", param.PublishDate.ToString("yyyy-MM-dd")));  
        bookXml.Add(new XElement("price", param.Price));  
        xml.Add(bookXml);  
        //保存  
        xml.Save(_basePath);  
        return true;  
    }  
  
    /// <summary>    
    /// 修改图书信息(修改)    
    /// </summary>    
    /// <param name="param"></param>    
    /// <returns></returns>    
    public bool EditBookInfo(BookInfo param)  
    {  
        bool result = false;  
        if (param.BookId > 0)  
        {  
            //根据BookId找到要修改的图书XML  
            XElement xml = XElement.Load(_basePath);  
            XElement bookXml = (from db in xml.Descendants("book") where db.Attribute("id").Value == param.BookId.ToString() select db).Single();  
            //修改属性  
            bookXml.SetAttributeValue("category", param.Category);  
            //修改子节点  
            bookXml.SetElementValue("title", param.Title);  
            bookXml.SetElementValue("author", param.Author);  
            bookXml.SetElementValue("publishDate", param.PublishDate.ToString("yyyy-MM-dd"));  
            bookXml.SetElementValue("price", param.Price);  
            //保存  
            xml.Save(_basePath);  
            result = true;  
        }  
        return result;  
    }  
  
    /// <summary>    
    /// 删除图书信息(删除)    
    /// </summary>    
    /// <param name="param"></param>    
    /// <returns></returns>    
    public bool DeleteBookInfo(BookInfo param)  
    {  
        bool result = false;  
        if (param.BookId > 0)  
        {  
            //根据BookId找到要删除的图书XML  
            XElement xml = XElement.Load(_basePath);  
            XElement bookXml = (from db in xml.Descendants("book") where db.Attribute("id").Value == param.BookId.ToString() select db).Single();  
            bookXml.Remove();  
            //保存  
            xml.Save(_basePath);  
            result = true;  
        }  
        return result;  
    }  
  
    /// <summary>  
    /// 获取图书列表  
    /// </summary>  
    /// <returns></returns>  
    public List<BookInfo> GetBookList()  
    {  
        List<BookInfo> bookList = new List<BookInfo>();  
        //创建图书1  
        BookInfo book1 = new BookInfo() {   
            BookId = 1,  
            Category = "CHILDREN",  
            Title = "Harry Potter",  
            Author = "J K. Rowling",  
            PublishDate = new DateTime(2005,08,15),  
            Price = 29.99  
        };  
        bookList.Add(book1);  
        //创建图书2  
        BookInfo book2 = new BookInfo()  
        {  
            BookId = 2,  
            Category = "WEB",  
            Title = "Learning XML",  
            Author = "Erik T. Ray",  
            PublishDate = new DateTime(2003,10,18),  
            Price = 39.95  
        };  
        bookList.Add(book2);  
        //创建图书3  
        BookInfo book3 = new BookInfo()  
        {  
            BookId = 3,  
            Category = "WEB",  
            Title = "XQuery Kick Start",  
            Author = "James McGovern",  
            PublishDate = new DateTime(2005,6,25),  
            Price = 49.99  
        };  
        bookList.Add(book3);  
        return bookList;  
    }  
}  

  cop

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值