Home > Backend Development > C#.Net Tutorial > C# writes XML reading and writing classes to operate xml files

C# writes XML reading and writing classes to operate xml files

黄舟
Release: 2017-02-27 11:38:03
Original
3428 people have browsed it

C#Write XML reading and writing classes to operate xml files


The following example uses C# to implement xml operations in asp.net. The environment is vs2005. I wrote an operation class myself, and then Call it when in use.

Implementation: Add, modify and delete login user information without using a database and only store an xml file locally.


The following is the format of the User.xml file, placed in the website and directory. This example is only to implement the function of operating xml, so the login password is not encrypted. In practical applications, you should consider this question. At the same time, this file should be given write permission, which is easier to miss.

C# writes XML reading and writing classes to operate xml files

<?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>
Copy after login

Let’s start coding. First, create an asp.net website in vs2005, select the c# language

Create a new web form, and put There are three textboxes and three buttons. There is no need to change the names for the time being. For the convenience of everyone (and my laziness), the names of the controls are not changed in this example (blush).

Then create a new project - class, name it XmlRW.cs, and store it in the app_Code folder

Add the using of xml at the top: using System.Xml as the following code

C# writes XML reading and writing classes to operate xml files

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;
Copy after login

C# writes XML reading and writing classes to operate xml files

C# writes XML reading and writing classes to operate xml files

##

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

Then, we started writing three A method to complete the addition, modification and deletion of xml file records, that is, the operation of UserCode, UserName, NamePwd. The code is as follows:



C# writes XML reading and writing classes to operate xml files

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);
    }
}
Copy after login

C# writes XML reading and writing classes to operate xml files
Ok! In this way, we have basically finished the operation of the xml class. Let's go back to the page we created at the beginning and add their corresponding codes to the three buttons, so that it can be super easy to operate the logged-in user. Hoho~


C# writes XML reading and writing classes to operate xml files

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!");
    }
}
Copy after login

C# writes XML reading and writing classes to operate xml files
Run the test, enter the user code in textbox1, fill in the user name in textbox2, and fill in the login in textbox3 Password, click button1 to complete the addition.... Note that the xml must be created in advance, and the others are the same.

The above is the content of C# writing XML reading and writing classes to operate xml files. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template