SoFunction
Updated on 2025-03-07

C# applies examples for basic xml operations and saving configuration files

This article describes the basic operations and configuration file saving applications of C# for xml, and is shared with you for your reference. The specific methods are as follows:

Introduction: Here we first introduce the basic operations of xml, and then write an example of the frequently used xml configuration file to save.

Common methods for xml:

Define xml document: XmlDocument xmlDoc = new XmlDocument();

Initialize the xml document: ("D:\\");//Finish the xml file

Create root element: XmlElement xmlElement = ("", "Employees", "");

Create node: XmlElement xeSub1 = ("title");

Find Employees node: XmlNode root = ("Employees");

Add node: (xeSub1);

Change the properties of the node: ("Name", "Li Mingming");

Remove the ID attribute of xe: ("ID");

Delete the node title: (xe2);

1 Create an XML document

Because it is relatively simple, write the method and results directly.

Copy the codeThe code is as follows:
public void CreateXMLDocument()
{
    XmlDocument xmlDoc = new XmlDocument();          

//Additional paragraph to add XML, <?xml version="1.0" encoding="gb2312"?>
    XmlDeclaration xmlDeclar;
    xmlDeclar = ("1.0", "gb2312", null);
    (xmlDeclar);          

//Add Employees root element
    XmlElement xmlElement = ("", "Employees", "");
    (xmlElement);        

//Add node
    XmlNode root = ("Employees");
    XmlElement xe1 = ("Node");
("Name", "Li Ming");
    ("ISB", "2-3631-4");        

//Add child nodes
    XmlElement xeSub1 = ("title");
= "Learn VS";
    (xeSub1);


    XmlElement xeSub2 = ("price");
    (xeSub2);
    XmlElement xeSub3 = ("weight");
    = "20";
    (xeSub3);


    (xe1);
("D:\\");//Save path
}

result:

Copy the codeThe code is as follows:
<?xml version="1.0" encoding="GB2312"?>
-<Employees>-

<Node ISB="2-3631-4" Name="Li Ming">

<title>Learning VS</title>-

<price>

<weight>20</weight>

</price>

</Node>

</Employees>

2 Add nodes

Copy the codeThe code is as follows:
XmlDocument xmlDoc = new XmlDocument();
("D:\\");//Finish the xml file
XmlNode root = ("Employees");//Find Employees node
XmlElement xe1 = ("Node2");//Add Node2 node
("Name", "Zhang San");
XmlElement xeSub1 = ("title");//Define child nodes
= "Good mood";
(xeSub1);//Add node to Node2
(xe1);//Add node to Employees
("D:\\");

result:

Copy the codeThe code is as follows:
<?xml version="1.0" encoding="GB2312"?>
-<Employees>

-<Node ISB="2-3631-4" Name="Li Ming">

<title>Learning VS</title>-

<price>

<weight>20</weight>

</price>

</Node>-

<Node2 Name="Zhang San">

<title>Good mood</title>

</Node2>-

<Node2 Name="Zhang San">

<title>Good mood</title>

</Node2>

</Employees>

3 Modify the node:

Copy the codeThe code is as follows:
public void ModifyNode()
{
    XmlDocument xmlDocument = new XmlDocument();
    ("D:\\");

XmlNodeList nodeList = ("Employees").ChildNodes;//Get all child nodes of Employees node

foreach (XmlNode xn in nodeList)//Transaction
    {
 XmlElement xe = (XmlElement)xn;
if (("Name") == "Li Ming")
 {
("Name", "Li Mingming");//Change the properties of the node

XmlNodeList xnl = ;//Get all children of xe
     foreach (XmlNode xn1 in xnl)
     {
XmlElement xe2 = (XmlElement)xn1;//Convert the attribute of node xn1 to XmlElement
if ( == "title")//Find the node with the node name title
  {
= "The weather is not good today";
  }

  if ( == "price")
  {
      XmlNodeList xnl2 = ;
      foreach (XmlNode xn2 in xnl2)
      {
   if ( == "weight")
   {
       = "88";
   }
      }
  }
     }
 }
    }

    ("D:\\");
}

Running results:

Copy the codeThe code is as follows:
<?xml version="1.0" encoding="GB2312"?>
-<Employees>
-<Node ISB="2-3631-4" Name="Li Mingming">
<title>The weather is not good today</title>-<price>
<weight>88</weight>
</price>
</Node>
-<Node2 Name="Zhang San">
<title>Good mood</title>
</Node2></Employees>

4 Delete nodes:

Copy the codeThe code is as follows:
public void DeleteNode()
{
    XmlDocument xmlDocument = new XmlDocument();
    ("D:\\");

    XmlNodeList xnl = ("Employees").ChildNodes;

    foreach (XmlNode xn in xnl)
    {
 if ( == "Node")
 {
XmlElement xe = (XmlElement)xn;//Convert the attribute of xn to XmlElement
("ID");//Remove the ID attribute of xe
     XmlNodeList xnl2 = ;
     for (int i = 0; i < ; i++)
     {
  XmlElement xe2 = (XmlElement)(i);
  if ( == "title")
  {
(xe2);//Delete the node title
  }
     }
 }
    }

    ("D:\\");
}

result:

Copy the codeThe code is as follows:
<?xml version="1.0" encoding="GB2312"?>
-<Employees>
-<Node ISB="2-3631-4" Name="Li Ming">-<price>
<weight>20</weight>
</price>
</Node>-
<Node2 Name="Zhang San">
<title>Good mood</title>
</Node2>-
<Node2 Name="Zhang San">
<title>Good mood</title>
</Node2>
</Employees>

The previous example of creating XML, adding nodes, modifying and deleting nodes. Below is a small example of saving project configuration files.

Give an example:

First create an XML document in the project file:

Copy the codeThe code is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<configurationN>
    <ServerAddress>1143</ServerAddress>
    <ID>192.168</ID>
  </configurationN>

When saving configuration files, two main methods are used: Load and Save.

Load: Initialize the xml document so that the project file can obtain the value of the specific xml node.

Copy the codeThe code is as follows:
public void Load(string path)
{
    try
    {
 XmlDocument xmlDocument = new XmlDocument();
 (path);

 XmlNodeList xnl = (managerNode).ChildNodes;
 foreach (XmlNode xn in xnl)
 {
     if ( == configuration_ServerAddress)
     {
  ServerAddress = ;
     }
 }
    }
    catch(Exception ex)
    { }
}

Save: After modifying the configuration file value in the project system, the XML needs to be saved again.

Copy the codeThe code is as follows:
public void Save(string path)
{
    try
    {
 XmlDocument xmlDocument = new XmlDocument();
 (path);

 XmlNodeList xnl = (managerNode).ChildNodes;
 foreach (XmlNode xn in xnl)
 {
     if ( == configuration_ServerAddress)
     {
   = ServerAddress;
     }
 }

 (path);
    }
    catch (Exception ex)
    { }
}

All the codes are posted here to facilitate the next implementation. Because the project is a WPF file and is all simple controls, only the background code is posted.

Copy the codeThe code is as follows:
class ConfigurationManager:INotifyPropertyChanged
{
public const string managerNode = "configurationN";//root node
public const string configuration_ServerAddress = "ServerAddress";//Child nodes

        private string _ServerAddress;
        public string ServerAddress
        {
            get { return _ServerAddress; }
            set
            {
                _ServerAddress = value;
                NotifyPropertyChanged("ServerAddress");
            }
        }

        public void Load(string path)
        {
            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                (path);

                XmlNodeList xnl = (managerNode).ChildNodes;
                foreach (XmlNode xn in xnl)
                {
                    if ( == configuration_ServerAddress)
                    {
                        ServerAddress = ;
                    }
                }
            }
            catch(Exception ex)
            { }
        }

        public void Save(string path)
        {
            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                (path);

                XmlNodeList xnl = (managerNode).ChildNodes;
                foreach (XmlNode xn in xnl)
                {
                    if ( == configuration_ServerAddress)
                    {
                        = ServerAddress;
                    }
                }

                (path);
            }
            catch (Exception ex)
            { }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public static ConfigurationManager Instance = new ConfigurationManager();
}

public partial class MainWindow : Window
{
        public MainWindow()
        {
            InitializeComponent();
            Start();
            this. = ();

        }
        private string path = "CONFIG\\";

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            = this.;
            (path);
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            ();
        }

        private void Start()
        {
            (path);
        }
}

PS: Here are a few online tools for your reference:

Online XML/JSON mutual conversion tool:
http://tools./code/xmljson

Online formatting/online compressing XML:
http://tools./code/xmlformat

XML online compression/formatting tools:
http://tools./code/xml_format_compress

I hope this article will be helpful to everyone's C# programming.