Table of Contents
C#Write XML reading and writing classes to operate xml files
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

Feb 27, 2017 am 11:38 AM

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 (www.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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1660
14
PHP Tutorial
1260
29
C# Tutorial
1233
24
Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

How to change the format of xml How to change the format of xml Apr 03, 2025 am 08:42 AM

There are several ways to modify XML formats: manually editing with a text editor such as Notepad; automatically formatting with online or desktop XML formatting tools such as XMLbeautifier; define conversion rules using XML conversion tools such as XSLT; or parse and operate using programming languages ​​such as Python. Be careful when modifying and back up the original files.

C# vs. C  : History, Evolution, and Future Prospects C# vs. C : History, Evolution, and Future Prospects Apr 19, 2025 am 12:07 AM

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

How to convert xml into word How to convert xml into word Apr 03, 2025 am 08:15 AM

There are three ways to convert XML to Word: use Microsoft Word, use an XML converter, or use a programming language.

See all articles