


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.
<?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>
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
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: 在此处添加构造函数逻辑 // } /**///// 大家注意 我们下面的内容在这里写 }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:
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! 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~
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!"); } }
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.

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version
