C#编写XML读写类操作xml文件

下面的例子是用C# 在asp.net 中实现对xml的操作,环境是vs2005 , 自己写了一个操作类,然后在使用的时候调用它。

实现:登录用户信息的添加、修改和删除,不使用数据库,只在本地存放一个xml文件。

时间:2007年12月21日

下面是User.xml文件的格式,放在网站跟目录中,本例只为实现操作xml的功能,所以登录密码没有加密,在实际应用中,你应该考虑这个问题。同时,这个文件应该赋予写入的权限,这点比较容易疏漏。

<?xml version="1.0"?>
<UserLogin>
  <User>
    <UserCode>001</UserCode>
    <UserName>操作员1</UserName>
    <UserPwd>111</UserPwd>
  </User>
  <User>
    <UserCode>002</UserCode>
    <UserName>操作员2</UserName>
    <UserPwd>222</UserPwd>
  </User>
</UserLogin>
下面我们开始编码,首先vs2005中创建asp.net 网站,选择c#语言

新建一个web窗体,放上三个textbox,三个button,暂时不用改名字,为了方便大家(以及我懒)这个例子中没有改控件的名字(脸红)。

 接着新建项目--类,取名为XmlRW.cs,存放到app_Code文件夹中

在最上部加上对xml的using  : using System.Xml  如下面的代码

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;

/// <summary>
/// Xml文件的读写类
/// </summary>
/// 
public class XmlRW
{
    public XmlRW()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

  大家注意 我们下面的内容在这里写

}

然后,我们开始写三个方法,来完成对xml文件记录的增加,修改和删除,也就是对UserCode,UserName,NamePwd的操作。代码如下:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;

/// <summary>
/// Xml文件的读写类
/// </summary>
/// 
public class XmlRW
{
    public XmlRW()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
    
    //WriteXml 完成对User的添加操作 
    //FileName 当前xml文件的存放位置
    //UserCode 欲添加用户的编码
    //UserName 欲添加用户的姓名
    //UserPassword 欲添加用户的密码

    public void WriteXML(string FileName,string UserCode,string UserName,string UserPassword)
    {
    
        //初始化XML文档操作类
        XmlDocument myDoc = new XmlDocument();
        //加载XML文件
        myDoc.Load(FileName);

        //添加元素--UserCode
        XmlElement ele = myDoc.CreateElement("UserCode");
        XmlText text = myDoc.CreateTextNode(UserCode);

        //添加元素--UserName
        XmlElement ele1 = myDoc.CreateElement("UserName");
        XmlText text1 = myDoc.CreateTextNode(UserName);

        //添加元素--UserPwd
        XmlElement ele2 = myDoc.CreateElement("UserPwd");
        XmlText text2 = myDoc.CreateTextNode(UserPassword);

        //添加节点 User要对应我们xml文件中的节点名字
        XmlNode newElem = myDoc.CreateNode("element", "User", "");

        //在节点中添加元素
        newElem.AppendChild(ele);
        newElem.LastChild.AppendChild(text);
        newElem.AppendChild(ele1);
        newElem.LastChild.AppendChild(text1);
        newElem.AppendChild(ele2);
        newElem.LastChild.AppendChild(text2);

        //将节点添加到文档中
        XmlElement root = myDoc.DocumentElement;
        root.AppendChild(newElem);

        //保存
        myDoc.Save(FileName);
        
    }

    //DeleteNode 完成对User的添加操作 
    //FileName 当前xml文件的存放位置
    //UserCode 欲添加用户的编码

    public void DeleteNode(string FileName, string UserCode)
    {
        //初始化XML文档操作类
        XmlDocument myDoc = new XmlDocument();
        //加载XML文件
        myDoc.Load(FileName);

        //搜索指定某列,一般是主键列
        XmlNodeList myNode = myDoc.SelectNodes("//UserCode");

        //判断是否有这个节点

        if (!(myNode == null))
        { 
            //遍历节点,找到符合条件的元素

            foreach (XmlNode  xn in myNode)
            {
                if (xn.InnerXml  == UserCode)
                    //删除元素的父节点
                    xn.ParentNode.ParentNode.RemoveChild(xn.ParentNode);
            }
        }

        //保存
        myDoc.Save(FileName);

    }

    //WriteXml 完成对User的修改密码操作
    //FileName 当前xml文件的存放位置
    //UserCode 欲操作用户的编码
    //UserPassword 欲修改用户的密码

    public void UpdateXML(string FileName, string UserCode, string UserPassword)
    {

        //初始化XML文档操作类
        XmlDocument myDoc = new XmlDocument();
        //加载XML文件
        myDoc.Load(FileName);

        //搜索指定的节点
        System.Xml.XmlNodeList nodes = myDoc.SelectNodes("//User");

        if (nodes != null)
        {
            foreach (System.Xml.XmlNode xn in nodes)
            {
                if (xn.SelectSingleNode("UserCode").InnerText == UserCode)
                {
                    xn.SelectSingleNode("UserPwd").InnerText = UserPassword;
                }

            }
        }

        myDoc.Save(FileName);

    }

}

Ok!这样操作xml的类我们就基本搞定了,下面回到一开始我们创建的那个页面上,为三个button加入它们相应的代码,即可超级轻松的实现对登录用户的操作,吼吼~

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class XmlTest1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {

        //添加引用,创建实例
        XmlRW myXml = new XmlRW();
        //调用我们实现定义好的方法,对应传入各个参数
        myXml.WriteXML(Server.MapPath("YtConfig.xml"), TextBox1.Text, TextBox2.Text, TextBox3.Text);

        Response.Write("Save OK!");

    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        XmlRW myXml = new XmlRW();
        myXml.DeleteNode(Server.MapPath("YtConfig.xml"), TextBox1.Text );

        Response.Write("Delete OK!");

    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        XmlRW myXml = new XmlRW();
        myXml.UpdateXML(Server.MapPath("YtConfig.xml"), TextBox1.Text, TextBox3.Text );

        Response.Write("Update OK!");

    }
}

运行测试,在textbox1中输入用户编码,在textbox2中填入用户名称,在textbox3中填入登录密码,点击button1完成添加....注意xml要事先先建好才行,其它
 
class Program 
{ 
static void Main(string[] args) 
{ 
XmlDocument doc = new XmlDocument(); // 创建dom对象

XmlElement root = doc.CreateElement("album"); // 创建根节点album
root.SetAttribute("name", "album1"); // 设置属性
doc.AppendChild(root);    //  加入到xml document

XmlElement preview = doc.CreateElement("Preview");  // 创建preview元素
preview.SetAttribute("path", "album1");    //
preview.SetAttribute("extension", "xpi");  //
preview.SetAttribute("sizew", "680");      //    设置属性
preview.SetAttribute("sizeh", "474");      //
preview.SetAttribute("totalpage", "25");   //
root.AppendChild(preview);   // 添加到xml document

//下面一样,不一行行写解释了

XmlElement page = doc.CreateElement("Page"); 
page.SetAttribute("id", "0"); 
page.SetAttribute("text", "封面"); 
page.SetAttribute("bgimg", "fm.xpi"); 
page.SetAttribute("sizew", "680"); 
page.SetAttribute("sizeh", "474"); 
page.SetAttribute("totalphoto", "2"); 
preview.AppendChild(page); 

XmlElement photo1 = doc.CreateElement("Photo"); 
photo1.SetAttribute("id", "0"); 
photo1.SetAttribute("x", "0"); 
photo1.SetAttribute("y", "0"); 
photo1.SetAttribute("minw", "5029"); 
photo1.SetAttribute("minh", "3504"); 
photo1.SetAttribute("pwidth", "680"); 
photo1.SetAttribute("pheight", "474"); 
photo1.SetAttribute("image", "hard_cover_color.xpi"); 
page.AppendChild(photo1); 

XmlElement photo2 = doc.CreateElement("Photo"); 
photo2.SetAttribute("id", "1"); 
photo2.SetAttribute("x", "138"); 
photo2.SetAttribute("y", "117"); 
photo2.SetAttribute("minw", "3155"); 
photo2.SetAttribute("minh", "1925"); 
photo2.SetAttribute("pwidth", "406"); 
photo2.SetAttribute("pheight", "243"); 
photo2.SetAttribute("image", "sampleS.xpi"); 
page.AppendChild(photo2); 

doc.Save(@"album\album1.xml");   // 保存文件
} 
c#读写xml文件
已知有一个XML文件(bookstore.xml)如下:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book genre="fantasy" ISBN="2-3631-4">
    <title>Oberon's Legacy</title>
    <author>Corets, Eva</author>
    <price>5.95</price>
  </book>
</bookstore>
 
1、往<bookstore>节点中插入一个<book>节点:
   XmlDocument xmlDoc=new XmlDocument();
   xmlDoc.Load("bookstore.xml");
   XmlNode root=xmlDoc.SelectSingleNode("bookstore");//查找<bookstore>
   XmlElement xe1=xmlDoc.CreateElement("book");//创建一个<book>节点
   xe1.SetAttribute("genre","李赞红");//设置该节点genre属性
   xe1.SetAttribute("ISBN","2-3631-4");//设置该节点ISBN属性
 
   XmlElement xesub1=xmlDoc.CreateElement("title");
   xesub1.InnerText="CS从入门到精通";//设置文本节点
   xe1.AppendChild(xesub1);//添加到<book>节点中
   XmlElement xesub2=xmlDoc.CreateElement("author");
   xesub2.InnerText="候捷";
   xe1.AppendChild(xesub2);
   XmlElement xesub3=xmlDoc.CreateElement("price");
   xesub3.InnerText="58.3";
   xe1.AppendChild(xesub3);
 
   root.AppendChild(xe1);//添加到<bookstore>节点中
   xmlDoc.Save("bookstore.xml");
//===============================================
结果为:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book genre="fantasy" ISBN="2-3631-4">
    <title>Oberon's Legacy</title>
    <author>Corets, Eva</author>
    <price>5.95</price>
  </book>
  <book genre="李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </book>
</bookstore>
 
2、修改节点:将genre属性值为“李赞红“的节点的genre值改为“update李赞红”,将该节点的子节点<author>的文本修改为“亚胜”。
    XmlNodeList nodeList=xmlDoc.SelectSingleNode("bookstore").ChildNodes;//获取bookstore节点的所有子节点
   foreach(XmlNode xn in nodeList)//遍历所有子节点
   {
    XmlElement xe=(XmlElement)xn;//将子节点类型转换为XmlElement类型
    if(xe.GetAttribute("genre")=="李赞红")//如果genre属性值为“李赞红”
    {
     xe.SetAttribute("genre","update李赞红");//则修改该属性为“update李赞红”
 
     XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点
     foreach(XmlNode xn1 in nls)//遍历
     {
      XmlElement xe2=(XmlElement)xn1;//转换类型
      if(xe2.Name=="author")//如果找到
      {
       xe2.InnerText="亚胜";//则修改
       break;//找到退出来就可以了
      }
     }
     break;
    }
   }
 
   xmlDoc.Save("bookstore.xml");//保存。
//==================================================
最后结果为:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book genre="fantasy" ISBN="2-3631-4">
    <title>Oberon's Legacy</title>
    <author>Corets, Eva</author>
    <price>5.95</price>
  </book>
  <book genre="update李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>亚胜</author>
    <price>58.3</price>
  </book>
</bookstore>
 
3、删除 <book genre="fantasy" ISBN="2-3631-4">节点的genre属性,删除 <book genre="update李赞红" ISBN="2-3631-4">节点。
XmlNodeList xnl=xmlDoc.SelectSingleNode("bookstore").ChildNodes;
 
   foreach(XmlNode xn in xnl)
   {
    XmlElement xe=(XmlElement)xn;
    if(xe.GetAttribute("genre")=="fantasy")
    {
     xe.RemoveAttribute("genre");//删除genre属性
    }
    else if(xe.GetAttribute("genre")=="update李赞红")
    {
     xe.RemoveAll();//删除该节点的全部内容
    }
   }
   xmlDoc.Save("bookstore.xml");
//===========================================
最后结果为:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book ISBN="2-3631-4">
    <title>Oberon's Legacy</title>
    <author>Corets, Eva</author>
    <price>5.95</price>
  </book>
  <book>
  </book>
</bookstore>
 
4、显示所有数据。
   XmlNode xn=xmlDoc.SelectSingleNode("bookstore");
 
   XmlNodeList xnl=xn.ChildNodes;
   
   foreach(XmlNode xnf in xnl)
   {
    XmlElement xe=(XmlElement)xnf;
    Console.WriteLine(xe.GetAttribute("genre"));//显示属性值
    Console.WriteLine(xe.GetAttribute("ISBN"));
 
    XmlNodeList xnf1=xe.ChildNodes;
    foreach(XmlNode xn2 in xnf1)
    {
     Console.WriteLine(xn2.InnerText);//显示子节点点文本
    }
   }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值