欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现XML文档的增删改查功能示例

程序员文章站 2022-04-01 09:09:28
本文实例讲述了c#实现xml文档的增删改查功能。分享给大家供大家参考,具体如下: 1、 创建实例xml文件(books.xml)

本文实例讲述了c#实现xml文档的增删改查功能。分享给大家供大家参考,具体如下:

1、 创建实例xml文件(books.xml)

<?xml version="1.0" encoding="iso-8859-1"?>
<bookstore>
 <book id="1" category="cooking">
  <title lang="en">everyday italian</title>
  <author>giada de laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
 </book>
 <book id="2" category="children">
  <title lang="en">harry potter</title>
  <author>j k. rowling</author>
  <year>2005</year>
  <price>29.99</price>
 </book>
 <book id="3" category="web">
  <title lang="en">xquery kick start</title>
  <author>james mcgovern</author>
  <author>per bothner</author>
  <author>kurt cagle</author>
  <author>james linn</author>
  <author>vaidyanathan nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
 </book>
 <book id="4" category="web">
  <title lang="en">learning xml</title>
  <author>erik t. ray</author>
  <year>2003</year>
  <price>39.95</price>
 </book>
</bookstore>

2、 创建图书信息实体类(bookinfo.cs)

public class bookinfo
{
  /// <summary>
  /// 图书id
  /// </summary>
  public int bookid { set; get; }
  /// <summary>
  /// 图书名称
  /// </summary>
  public string title { set; get; }
  /// <summary>
  /// 图书分类
  /// </summary>
  public string category { set; get; }
  /// <summary>
  /// 图书语言
  /// </summary>
  public string language { set; get; }
  /// <summary>
  /// 图书作者
  /// </summary>
  public string author { set; get; }
  /// <summary>
  /// 出版时间
  /// </summary>
  public string year { set; get; }
  /// <summary>
  /// 销售价格
  /// </summary>
  public decimal price { set; get; }
}

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

using system.xml;  //引用相关文件
public class bookinfobll
{
  private string _basepath = appdomain.currentdomain.setupinformation.applicationbase + @"/xml/books.xml"; //xml文件路径
  private xmldocument _booksxmldoc = null;  //创建xml文档对象
  public bookinfobll()
  {
    try
    {
      _booksxmldoc = new xmldocument(); //初始化xml文档对象
      _booksxmldoc.load(_basepath);   //加载指定的xml文档
    }
    catch (exception ex)
    {
      throw new exception("加载xml文档出错:" + ex.message);
    }
  }
  /// <summary>
  /// 获取图书列表(查)
  /// </summary>
  /// <param name="param">参数条件</param>
  /// <returns>图书列表</returns>
  public list<bookinfo> getbookinfolist(bookinfo param)
  {
    list<bookinfo> bookinfolist = new list<bookinfo>();
    string xpath = "bookstore/book"; //默认获取所有图书
    if (param.bookid != 0) //根据图书id查询
    {
      xpath = string.format("/bookstore/book[@id='{0}']", param.bookid);
    }
    else if (!string.isnullorempty(param.category)) //根据图书类别查询
    {
      xpath = string.format("/bookstore/book[@category='{0}']", param.category);
    }
    else if (!string.isnullorempty(param.title)) //根据图书名称查询
    {
      xpath = string.format("/bookstore/book[title='{0}']", param.title);
    }
    xmlnodelist booksxmlnodelist = _booksxmldoc.selectnodes(xpath);
    foreach (xmlnode booknode in booksxmlnodelist)
    {
      bookinfo bookinfo = new bookinfo();
      bookinfo.bookid = convert.toint32(booknode.attributes["id"].value); //获取属性值
      bookinfo.category = booknode.attributes["category"].value;
      bookinfo.language = booknode.selectsinglenode("title").attributes["lang"].value; //获取子节点的属性值
      bookinfo.title = booknode.selectsinglenode("title").innertext;   //获取元素值
      bookinfo.author = booknode.selectsinglenode("author").innertext;
      bookinfo.year = booknode.selectsinglenode("year").innertext;
      bookinfo.price = convert.todecimal(booknode.selectsinglenode("price").innertext);
      bookinfolist.add(bookinfo);
    }
    return bookinfolist;
  }
  /// <summary>
  /// 增加图书信息(增)
  /// </summary>
  /// <param name="param"></param>
  /// <returns></returns>
  public bool addbookinfo(bookinfo param)
  {
    bool result = false;
    xmlnode root = _booksxmldoc.selectsinglenode("bookstore"); //查找<bookstore>
    //创建节点
    xmlelement bookxmlelement = _booksxmldoc.createelement("book");
    xmlelement titlexmlelement = _booksxmldoc.createelement("title");
    xmlelement authorxmlelement = _booksxmldoc.createelement("author");
    xmlelement yearxmlelement = _booksxmldoc.createelement("year");
    xmlelement pricexmlelement = _booksxmldoc.createelement("price");
    //给节点赋值
    bookxmlelement.setattribute("id", param.bookid.tostring());
    bookxmlelement.setattribute("category", param.category);
    titlexmlelement.innertext = param.title; //给节点添加元素值
    titlexmlelement.setattribute("lang", param.language);//给节点添加属性值
    authorxmlelement.innertext = param.author;
    yearxmlelement.innertext = param.year;
    pricexmlelement.innertext = param.price.tostring();
    //appendchild 将指定的节点添加到该节点的子节点列表的末尾
    bookxmlelement.appendchild(titlexmlelement);
    bookxmlelement.appendchild(authorxmlelement);
    bookxmlelement.appendchild(yearxmlelement);
    bookxmlelement.appendchild(pricexmlelement);
    root.appendchild(bookxmlelement);
    _booksxmldoc.save(_basepath);
    result = true;
    return result;
  }
  /// <summary>
  /// 修改图书信息(改)
  /// </summary>
  /// <param name="param"></param>
  /// <returns></returns>
  public bool editbookinfo(bookinfo param)
  {
    bool result = false;
    if(param.bookid>0)
    {
      string xpath = string.format("/bookstore/book[@id='{0}']", param.bookid);
      xmlnode editxmlnode = _booksxmldoc.selectsinglenode(xpath);
      xmlelement editxmlelement = (xmlelement)editxmlnode;
      if (editxmlelement != null)
      {
        editxmlelement.attributes["category"].value = param.category;
        editxmlelement.selectsinglenode("title").attributes["lang"].value = param.language;
        editxmlelement.selectsinglenode("title").innertext = param.title;
        editxmlelement.selectsinglenode("author").innertext = param.author;
        editxmlelement.selectsinglenode("year").innertext = param.year;
        editxmlelement.selectsinglenode("price").innertext = param.price.tostring();
        _booksxmldoc.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)
    {
      string xpath = string.format("/bookstore/book[@id='{0}']", param.bookid);
      xmlnode delxmlnode = _booksxmldoc.selectsinglenode(xpath);
      if (delxmlnode != null)
      {
        _booksxmldoc.selectsinglenode("bookstore").removechild(delxmlnode);  //移除指定的子节点
        _booksxmldoc.save(_basepath);
        result = true;
      }
    }
    return result;
  }
}

ps:这里再为大家提供几款比较实用的xml相关在线工具供大家使用:

在线xml格式化/压缩工具:

在线xml/json互相转换工具:

xml在线压缩/格式化工具:

xml代码在线格式化美化工具:

更多关于c#相关内容感兴趣的读者可查看本站专题:《c#中xml文件操作技巧汇总》、《c#常见控件用法教程》、《c#程序设计之线程使用技巧总结》、《winform控件用法总结》、《c#数据结构与算法教程》、《c#数组操作技巧总结》及《c#面向对象程序设计入门教程

希望本文所述对大家c#程序设计有所帮助。