首页 > 开发 > Xml > 正文

一个比较有用的XML文件操作类 C#代码 可以继续扩展

2020-02-03 13:49:50
字体:
来源:转载
供稿:网友

public class cxml

{

    private string strxmlfile;

     private xmldocument objxmldoc = new xmldocument();

     public cxml(string xmlfile)

     {

         //构造函数

         try

         {

              objxmldoc.load(xmlfile);

         }

         catch

         {

         }

         strxmlfile = xmlfile;

     }

     public dataview getdata(string xmlpathnode)

     {

         //查找数据返回一个dataview

         dataset ds = new dataset();

         stringreader read = new stringreader(objxmldoc.selectsinglenode(xmlpathnode).outerxml);

         ds.readxml(read);

         return ds.tables[0].defaultview;

     }

     public void replace(string xmlpathnode,string content)

     {

         //更新节点內容

         objxmldoc.selectsinglenode(xmlpathnode).innertext = content;

     }

     public void delete(string node)

     {

         //刪除一个节点

         string mainnode = node.substring(0,node.lastindexof("/"));

         objxmldoc.selectsinglenode(mainnode).removechild(objxmldoc.selectsinglenode(node));

     }

     public void insertnode(string mainnode,string childnode,string element,string content)

     {

         //插入一节点和此节点的一子节点

         xmlnode objrootnode = objxmldoc.selectsinglenode(mainnode);

         xmlelement objchildnode = objxmldoc.createelement(childnode);

         objrootnode.appendchild(objchildnode);

         xmlelement objelement = objxmldoc.createelement(element);

         objelement.innertext = content;

         objchildnode.appendchild(objelement);

     }

     public void insertelement(string mainnode,string element,string attrib,string attribcontent,string content)

     {

         //插入一个节点带一个属性

         xmlnode objnode = objxmldoc.selectsinglenode(mainnode);

         xmlelement objelement = objxmldoc.createelement(element);

         objelement.setattribute(attrib,attribcontent);

         objelement.innertext = content;

         objnode.appendchild(objelement);

     }

     public void insertelement(string mainnode,string element,string content)

     {

         //插入一个节点不带属性

         xmlnode objnode = objxmldoc.selectsinglenode(mainnode);

         xmlelement objelement = objxmldoc.createelement(element);

         objelement.innertext = content;

         objnode.appendchild(objelement);

     }

     public void save()

     {

         //保存xml文件

         try

         {

              objxmldoc.save(strxmlfile);

         }

         catch

         {

         }

         objxmldoc = null;

     }

}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表