C # Writing XML read-write class operation XML file

Source: Internet
Author: User


C # Writing XML read-write class operation XML file




The following example uses C # to implement XML operations in ASP. VS2005, writes an operation class, and then calls it when it is used.

Implementation: Login user information to add, modify and delete, do not use the database, only local storage of an XML file.


The following is the format of the User.xml file, placed in the site and directory, this example is only to implement the function of XML, so the login password is not encrypted, in the actual application, you should consider this problem. At the same time, this file should give permission to write, which is more easily overlooked.


<? xml version = "1.0"?>
<UserLogin>
   <User>
     <UserCode> 001 </ UserCode>
     <UserName> operator1 </ UserName>
     <UserPwd> 111 </ UserPwd>
   </ User>
   <User>
     <UserCode> 002 </ UserCode>
     <UserName> operator 2 </ UserName>
     <UserPwd> 222 </ UserPwd>
   </ User>
</ UserLogin>


Let's start coding, first create an ASP. VS2005, select the C # language

Create a new Web form, put three TextBox, three button, temporarily do not change the name, in order to facilitate everyone (and I lazy) This example does not change the name of the control (blush).

Then the new project-class, named XmlRW.cs, is stored in the App_Code folder

Add the using:using to the Xml at the top system.xml such 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 file read and write classes
/// </ summary>
///
public class XmlRW
... {
     public XmlRW ()
     ... {
         //
         // TODO: add constructor logic here
         //
     }
/ ** ///// Attention everyone, we write the following content here
}


Then we began to write three methods to complete the addition, modification and deletion of the 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 file read and write classes
/// </ summary>
///
public class XmlRW
... {
    public XmlRW ()
    ... {
        //
        // TODO: add constructor logic here
        //
    }
    // WriteXml finish adding user
    // FileName storage location of the current xml file
    // UserCode The code of the user to be added
    // UserName the name of the user to add
    // UserPassword password of the user to be added
    public void WriteXML (string FileName, string UserCode, string UserName, string UserPassword)
    ... {
        // Initialize the XML document operation class
        XmlDocument myDoc = new XmlDocument ();
        // Load the XML file
        myDoc.Load (FileName);
        // Add element-UserCode
        XmlElement ele = myDoc.CreateElement ("UserCode");
        XmlText text = myDoc.CreateTextNode (UserCode);
        // Add element-UserName
        XmlElement ele1 = myDoc.CreateElement ("UserName");
        XmlText text1 = myDoc.CreateTextNode (UserName);
        // Add element-UserPwd
        XmlElement ele2 = myDoc.CreateElement ("UserPwd");
        XmlText text2 = myDoc.CreateTextNode (UserPassword);
        // Add node User should correspond to the node name in our xml file
        XmlNode newElem = myDoc.CreateNode ("element", "User", "");
        // Add elements to the node
        newElem.AppendChild (ele);
        newElem.LastChild.AppendChild (text);
        newElem.AppendChild (ele1);
        newElem.LastChild.AppendChild (text1);
        newElem.AppendChild (ele2);
        newElem.LastChild.AppendChild (text2);
        // Add nodes to the document
        XmlElement root = myDoc.DocumentElement;
        root.AppendChild (newElem);
        //save
        myDoc.Save (FileName);
    }
    // DeleteNode completes the Add operation to User
    // FileName storage location of the current xml file
    // UserCode The code of the user to be added
    public void DeleteNode (string FileName, string UserCode)
    ... {
        // Initialize the XML document operation class
        XmlDocument myDoc = new XmlDocument ();
        // Load the XML file
        myDoc.Load (FileName);
        // Search for a specific column, usually a primary key column
        XmlNodeList myNode = myDoc.SelectNodes ("// UserCode");
        // Determine if there is this node
        if (! (myNode == null))
        ... {
            // Iterate through the nodes and find the elements that meet the conditions
            foreach (XmlNode xn in myNode)
            ... {
                if (xn.InnerXml == UserCode)
                    // Delete the parent node of the element
                    xn.ParentNode.ParentNode.RemoveChild (xn.ParentNode);
            }
        }
        //save
        myDoc.Save (FileName);
    }
    // WriteXml completes the password change operation for User
    // FileName storage location of the current xml file
    // UserCode The code of the user to be operated
    // UserPassword user password
    public void UpdateXML (string FileName, string UserCode, string UserPassword)
    ... {
        // Initialize the XML document operation class
        XmlDocument myDoc = new XmlDocument ();
        // Load the XML file
        myDoc.Load (FileName);
        // Search for the specified node
        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! This kind of operation of the XML class we basically finished, the following back to the beginning of the page we created, for three buttons to add their corresponding code, can be super easy to implement the operation of the login user, Roar ~


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)
    ... {
        // Add references and create instances
        XmlRW myXml = new XmlRW ();
        // Call the method we have defined, corresponding to each parameter passed in
        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 the textbox1, fill in the user name in the TextBox2, fill in the login password in the TextBox3, click Button1 Complete Add .... Note that XML should be built first before the other slightly.



The above is the C # write XML read-write class operation XML file content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!


  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.