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

前端之家收集整理的这篇文章主要介绍了LINQ to XML实现XML文档的增删改查前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

<?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)

/// <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)

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,Title = "XQuery Kick Start",Author = "James McGovern",6,25),Price = 49.99
        };
        bookList.Add(book3);
        return bookList;
    }
}
原文链接:https://www.f2er.com/xml/299447.html

猜你在找的XML相关文章