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

黄舟
Libérer: 2017-02-27 11:38:03
original
3343 Les gens l'ont consulté

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


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

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


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

C#编写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>
Copier après la connexion

下面我们开始编码,首先vs2005中创建asp.net 网站,选择c#语言

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

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

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

C#编写XML读写类操作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;
Copier après la connexion

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

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

/**//// <summary>
/// Xml文件的读写类
/// </summary>
/// 
public class XmlRW
...{
    public XmlRW()
    ...{
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
/**/////  大家注意 我们下面的内容在这里写
}
Copier après la connexion

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

C#编写XML读写类操作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: 在此处添加构造函数逻辑
        //
    }
    //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);
    }
}
Copier après la connexion

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

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

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

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!");
    }
}
Copier après la connexion

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

运行测试,在textbox1中输入用户编码,在textbox2中填入用户名称,在textbox3中填入登录密码,点击button1完成添加....注意xml要事先先建好才行,其它略同.

 以上就是C#编写XML读写类操作xml文件 的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!