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

C#自定义处理xml数据类实例

程序员文章站 2023-12-04 17:34:22
本文实例讲述了c#自定义处理xml数据类。分享给大家供大家参考。具体分析如下: 这个c#类专门用户处理xml数据,可以大大简化xml的操作,类中封装了常用的xml操作,包...

本文实例讲述了c#自定义处理xml数据类。分享给大家供大家参考。具体分析如下:

这个c#类专门用户处理xml数据,可以大大简化xml的操作,类中封装了常用的xml操作,包括打开、读取xml数据,读取、写入节点数据,通过xpath读取节点数据,导出节点数据等等,还可以根据需要自己扩充类的功能。

using system;
using system.data;
using system.io;
using system.xml;
namespace dotnet.utilities
{
  public class xmlprocess
  {
    #region 构造函数
    public xmlprocess()
    { }
    public xmlprocess(string strpath)
    {
      this._xmlpath = strpath;
    }
    #endregion
    #region 公有属性
    private string _xmlpath;
    public string xmlpath
    {
      get { return this._xmlpath; }
    }
    #endregion
    #region 私有方法
    /// <summary>
    /// 导入xml文件
    /// </summary>
    /// <param name="xmlpath">xml文件路径</param>
    private xmldocument xmlload()
    {
      string xmlfile = xmlpath;
      xmldocument xmldoc = new xmldocument();
      try
      {
        string filename = appdomain.currentdomain.basedirectory.tostring() + xmlfile;
        if (file.exists(filename)) xmldoc.load(filename);
      }
      catch (exception e)
      { }
      return xmldoc;
    }
    /// <summary>
    /// 导入xml文件
    /// </summary>
    /// <param name="xmlpath">xml文件路径</param>
    private static xmldocument xmlload(string strpath)
    {
      xmldocument xmldoc = new xmldocument();
      try
      {
        string filename = appdomain.currentdomain.basedirectory.tostring() + strpath;
        if (file.exists(filename)) xmldoc.load(filename);
      }
      catch (exception e)
      { }
      return xmldoc;
    }
    /// <summary>
    /// 返回完整路径
    /// </summary>
    /// <param name="strpath">xml的路径</param>
    private static string getxmlfullpath(string strpath)
    {
      if (strpath.indexof(":") > 0)
      {
        return strpath;
      }
      else
      {
        return system.web.httpcontext.current.server.mappath(strpath);
      }
    }
    #endregion
    #region 读取数据
    /// <summary>
    /// 读取指定节点的数据
    /// </summary>
    /// <param name="node">节点</param>
    /// 使用示列:
    /// xmlprosess.read("/node", "")
    /// xmlprosess.read("/node/element[@attribute='name']")
    public string read(string node)
    {
      string value = "";
      try
      {
        xmldocument doc = xmlload();
        xmlnode xn = doc.selectsinglenode(node);
        value = xn.innertext;
      }
      catch { }
      return value;
    }
    /// <summary>
    /// 读取指定路径和节点的串联值
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="node">节点</param>
    /// <param name="attribute">属性名,非空时返回该属性值,否则返回串联值</param>
    /// 使用示列:
    /// xmlprosess.read(path, "/node", "")
    /// xmlprosess.read(path, "/node/element[@attribute='name']")
    public static string read(string path, string node)
    {
      string value = "";
      try
      {
        xmldocument doc = xmlload(path);
        xmlnode xn = doc.selectsinglenode(node);
        value = xn.innertext;
      }
      catch { }
      return value;
    }
    /// <summary>
    /// 读取指定路径和节点的属性值
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="node">节点</param>
    /// <param name="attribute">属性名,非空时返回该属性值,否则返回串联值</param>
    /// 使用示列:
    /// xmlprosess.read(path, "/node", "")
    /// xmlprosess.read(path, "/node/element[@attribute='name']", "attribute")
    public static string read(string path, string node, string attribute)
    {
      string value = "";
      try
      {
        xmldocument doc = xmlload(path);
        xmlnode xn = doc.selectsinglenode(node);
        value = (attribute.equals("") ? xn.innertext : xn.attributes[attribute].value);
      }
      catch { }
      return value;
    }
    /// <summary>
    /// 获取某一节点的所有孩子节点的值
    /// </summary>
    /// <param name="node">要查询的节点</param>
    public string[] readallchildallvalue(string node)
    {
      int i = 0;
      string[] str = { };
      xmldocument doc = xmlload();
      xmlnode xn = doc.selectsinglenode(node);
      xmlnodelist nodelist = xn.childnodes; //得到该节点的子节点
      if (nodelist.count > 0)
      {
        str = new string[nodelist.count];
        foreach (xmlelement el in nodelist)//读元素值
        {
          str[i] = el.value;
          i++;
        }
      }
      return str;
    }
    /// <summary>
    /// 获取某一节点的所有孩子节点的值
    /// </summary>
    /// <param name="node">要查询的节点</param>
    public xmlnodelist readallchild(string node)
    {
      xmldocument doc = xmlload();
      xmlnode xn = doc.selectsinglenode(node);
      xmlnodelist nodelist = xn.childnodes; //得到该节点的子节点
      return nodelist;
    }
    /// <summary>
    /// 读取xml返回经排序或筛选后的dataview
    /// </summary>
    /// <param name="strwhere">筛选条件,如:"name='kgdiwss'"</param>
    /// <param name="strsort"> 排序条件,如:"id desc"</param>
    public dataview getdataviewbyxml(string strwhere, string strsort)
    {
      try
      {
        string xmlfile = this.xmlpath;
        string filename = appdomain.currentdomain.basedirectory.tostring() + xmlfile;
        dataset ds = new dataset();
        ds.readxml(filename);
        dataview dv = new dataview(ds.tables[0]); //创建dataview来完成排序或筛选操作  
        if (strsort != null)
        {
          dv.sort = strsort; //对dataview中的记录进行排序
        }
        if (strwhere != null)
        {
          dv.rowfilter = strwhere; //对dataview中的记录进行筛选,找到我们想要的记录
        }
        return dv;
      }
      catch (exception)
      {
        return null;
      }
    }
    /// <summary>
    /// 读取xml返回dataset
    /// </summary>
    /// <param name="strxmlpath">xml文件相对路径</param>
    public dataset getdatasetbyxml(string strxmlpath)
    {
      try
      {
        dataset ds = new dataset();
        ds.readxml(getxmlfullpath(strxmlpath));
        if (ds.tables.count > 0)
        {
          return ds;
        }
        return null;
      }
      catch (exception)
      {
        return null;
      }
    }
    #endregion
    #region 插入数据
    /// <summary>
    /// 插入数据
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="node">节点</param>
    /// <param name="element">元素名,非空时插入新元素,否则在该元素中插入属性</param>
    /// <param name="attribute">属性名,非空时插入该元素属性值,否则插入元素值</param>
    /// <param name="value">值</param>
    /// 使用示列:
    /// xmlprosess.insert(path, "/node", "element", "", "value")
    /// xmlprosess.insert(path, "/node", "element", "attribute", "value")
    /// xmlprosess.insert(path, "/node", "", "attribute", "value")
    public static void insert(string path, string node, string element, string attribute, string value)
    {
      try
      {
        xmldocument doc = new xmldocument();
        doc.load(appdomain.currentdomain.basedirectory.tostring() + path);
        xmlnode xn = doc.selectsinglenode(node);
        if (element.equals(""))
        {
          if (!attribute.equals(""))
          {
            xmlelement xe = (xmlelement)xn;
            xe.setattribute(attribute, value);
          }
        }
        else
        {
          xmlelement xe = doc.createelement(element);
          if (attribute.equals(""))
            xe.innertext = value;
          else
            xe.setattribute(attribute, value);
          xn.appendchild(xe);
        }
        doc.save(appdomain.currentdomain.basedirectory.tostring() + path);
      }
      catch { }
    }
    /// <summary>
    /// 插入数据
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="node">节点</param>
    /// <param name="element">元素名,非空时插入新元素,否则在该元素中插入属性</param>
    /// <param name="strlist">由xml属性名和值组成的二维数组</param>
    public static void insert(string path, string node, string element, string[][] strlist)
    {
      try
      {
        xmldocument doc = new xmldocument();
        doc.load(appdomain.currentdomain.basedirectory.tostring() + path);
        xmlnode xn = doc.selectsinglenode(node);
        xmlelement xe = doc.createelement(element);
        string strattribute = "";
        string strvalue = "";
        for (int i = 0; i < strlist.length; i++)
        {
          for (int j = 0; j < strlist[i].length; j++)
          {
            if (j == 0)
              strattribute = strlist[i][j];
            else
              strvalue = strlist[i][j];
          }
          if (strattribute.equals(""))
            xe.innertext = strvalue;
          else
            xe.setattribute(strattribute, strvalue);
        }
        xn.appendchild(xe);
        doc.save(appdomain.currentdomain.basedirectory.tostring() + path);
      }
      catch { }
    }
    /// <summary>
    /// 插入一行数据
    /// </summary>
    /// <param name="strxmlpath">xml文件相对路径</param>
    /// <param name="columns">要插入行的列名数组,如:string[] columns = {"name","ismarried"};</param>
    /// <param name="columnvalue">要插入行每列的值数组,如:string[] columnvalue={"xml大全","false"};</param>
    /// <returns>成功返回true,否则返回false</returns>
    public static bool writexmlbydataset(string strxmlpath, string[] columns, string[] columnvalue)
    {
      try
      {
        //根据传入的xml路径得到.xsd的路径,两个文件放在同一个目录下
        string strxsdpath = strxmlpath.substring(0, strxmlpath.indexof(".")) + ".xsd";
        dataset ds = new dataset();
        ds.readxmlschema(getxmlfullpath(strxsdpath)); //读xml架构,关系到列的数据类型
        ds.readxml(getxmlfullpath(strxmlpath));
        datatable dt = ds.tables[0];
        datarow newrow = dt.newrow(); //在原来的表格基础上创建新行
        for (int i = 0; i < columns.length; i++) //循环给一行中的各个列赋值
        {
          newrow[columns[i]] = columnvalue[i];
        }
        dt.rows.add(newrow);
        dt.acceptchanges();
        ds.acceptchanges();
        ds.writexml(getxmlfullpath(strxmlpath));
        return true;
      }
      catch (exception)
      {
        return false;
      }
    }
    #endregion
    #region 修改数据
    /// <summary>
    /// 修改指定节点的数据
    /// </summary>
    /// <param name="node">节点</param>
    /// <param name="value">值</param>
    public void update(string node, string value)
    {
      try
      {
        xmldocument doc = xmlload();
        xmlnode xn = doc.selectsinglenode(node);
        xn.innertext = value;
        doc.save(appdomain.currentdomain.basedirectory.tostring() + xmlpath);
      }
      catch { }
    }
    /// <summary>
    /// 修改指定节点的数据
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="node">节点</param>
    /// <param name="value">值</param>
    /// 使用示列:
    /// xmlprosess.insert(path, "/node","value")
    /// xmlprosess.insert(path, "/node","value")
    public static void update(string path, string node, string value)
    {
      try
      {
        xmldocument doc = xmlload(path);
        xmlnode xn = doc.selectsinglenode(node);
        xn.innertext = value;
        doc.save(appdomain.currentdomain.basedirectory.tostring() + path);
      }
      catch { }
    }
    /// <summary>
    /// 修改指定节点的属性值(静态)
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="node">节点</param>
    /// <param name="attribute">属性名,非空时修改该节点属性值,否则修改节点值</param>
    /// <param name="value">值</param>
    /// 使用示列:
    /// xmlprosess.insert(path, "/node", "", "value")
    /// xmlprosess.insert(path, "/node", "attribute", "value")
    public static void update(string path, string node, string attribute, string value)
    {
      try
      {
        xmldocument doc = xmlload(path);
        xmlnode xn = doc.selectsinglenode(node);
        xmlelement xe = (xmlelement)xn;
        if (attribute.equals(""))
          xe.innertext = value;
        else
          xe.setattribute(attribute, value);
        doc.save(appdomain.currentdomain.basedirectory.tostring() + path);
      }
      catch { }
    }
    /// <summary>
    /// 更改符合条件的一条记录
    /// </summary>
    /// <param name="strxmlpath">xml文件路径</param>
    /// <param name="columns">列名数组</param>
    /// <param name="columnvalue">列值数组</param>
    /// <param name="strwherecolumnname">条件列名</param>
    /// <param name="strwherecolumnvalue">条件列值</param>
    public static bool updatexmlrow(string strxmlpath, string[] columns, string[] columnvalue, string strwherecolumnname, string strwherecolumnvalue)
    {
      try
      {
        string strxsdpath = strxmlpath.substring(0, strxmlpath.indexof(".")) + ".xsd";
        dataset ds = new dataset();
        ds.readxmlschema(getxmlfullpath(strxsdpath));//读xml架构,关系到列的数据类型
        ds.readxml(getxmlfullpath(strxmlpath));
        //先判断行数
        if (ds.tables[0].rows.count > 0)
        {
          for (int i = 0; i < ds.tables[0].rows.count; i++)
          {
            //如果当前记录为符合where条件的记录
            if (ds.tables[0].rows[i][strwherecolumnname].tostring().trim().equals(strwherecolumnvalue))
            {
              //循环给找到行的各列赋新值
              for (int j = 0; j < columns.length; j++)
              {
                ds.tables[0].rows[i][columns[j]] = columnvalue[j];
              }
              ds.acceptchanges();           //更新dataset
              ds.writexml(getxmlfullpath(strxmlpath));//重新写入xml文件
              return true;
            }
          }
        }
        return false;
      }
      catch (exception)
      {
        return false;
      }
    }
    #endregion
    #region 删除数据
    /// <summary>
    /// 删除节点值
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="node">节点</param>
    /// <param name="attribute">属性名,非空时删除该节点属性值,否则删除节点值</param>
    /// <param name="value">值</param>
    /// 使用示列:
    /// xmlprosess.delete(path, "/node", "")
    /// xmlprosess.delete(path, "/node", "attribute")
    public static void delete(string path, string node)
    {
      try
      {
        xmldocument doc = xmlload(path);
        xmlnode xn = doc.selectsinglenode(node);
        xn.parentnode.removechild(xn);
        doc.save(appdomain.currentdomain.basedirectory.tostring() + path);
      }
      catch { }
    }
    /// <summary>
    /// 删除数据
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="node">节点</param>
    /// <param name="attribute">属性名,非空时删除该节点属性值,否则删除节点值</param>
    /// <param name="value">值</param>
    /// 使用示列:
    /// xmlprosess.delete(path, "/node", "")
    /// xmlprosess.delete(path, "/node", "attribute")
    public static void delete(string path, string node, string attribute)
    {
      try
      {
        xmldocument doc = xmlload(path);
        xmlnode xn = doc.selectsinglenode(node);
        xmlelement xe = (xmlelement)xn;
        if (attribute.equals(""))
          xn.parentnode.removechild(xn);
        else
          xe.removeattribute(attribute);
        doc.save(appdomain.currentdomain.basedirectory.tostring() + path);
      }
      catch { }
    }
    /// <summary>
    /// 删除所有行
    /// </summary>
    /// <param name="strxmlpath">xml路径</param>
    public static bool deletexmlallrows(string strxmlpath)
    {
      try
      {
        dataset ds = new dataset();
        ds.readxml(getxmlfullpath(strxmlpath));
        if (ds.tables[0].rows.count > 0)
        {
          ds.tables[0].rows.clear();
        }
        ds.writexml(getxmlfullpath(strxmlpath));
        return true;
      }
      catch (exception)
      {
        return false;
      }
    }
    /// <summary>
    /// 通过删除dataset中指定索引行,重写xml以实现删除指定行
    /// </summary>
    /// <param name="ideleterow">要删除的行在dataset中的index值</param>
    public static bool deletexmlrowbyindex(string strxmlpath, int ideleterow)
    {
      try
      {
        dataset ds = new dataset();
        ds.readxml(getxmlfullpath(strxmlpath));
        if (ds.tables[0].rows.count > 0)
        {
          ds.tables[0].rows[ideleterow].delete();
        }
        ds.writexml(getxmlfullpath(strxmlpath));
        return true;
      }
      catch (exception)
      {
        return false;
      }
    }
    /// <summary>
    /// 删除指定列中指定值的行
    /// </summary>
    /// <param name="strxmlpath">xml相对路径</param>
    /// <param name="strcolumn">列名</param>
    /// <param name="columnvalue">指定值</param>
    public static bool deletexmlrows(string strxmlpath, string strcolumn, string[] columnvalue)
    {
      try
      {
        dataset ds = new dataset();
        ds.readxml(getxmlfullpath(strxmlpath));
        if (ds.tables[0].rows.count > 0)
        {
          //判断行多还是删除的值多,多的for循环放在里面
          if (columnvalue.length > ds.tables[0].rows.count)
          {
            for (int i = 0; i < ds.tables[0].rows.count; i++)
            {
              for (int j = 0; j < columnvalue.length; j++)
              {
                if (ds.tables[0].rows[i][strcolumn].tostring().trim().equals(columnvalue[j]))
                {
                  ds.tables[0].rows[i].delete();
                }
              }
            }
          }
          else
          {
            for (int j = 0; j < columnvalue.length; j++)
            {
              for (int i = 0; i < ds.tables[0].rows.count; i++)
              {
                if (ds.tables[0].rows[i][strcolumn].tostring().trim().equals(columnvalue[j]))
                {
                  ds.tables[0].rows[i].delete();
                }
              }
            }
          }
          ds.writexml(getxmlfullpath(strxmlpath));
        }
        return true;
      }
      catch (exception)
      {
        return false;
      }
    }
    #endregion
  }
}

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