XML basic operations and save configuration file application instance

Source: Internet
Author: User
Tags ming

Introduction: In the actual project encountered some of the problem of XML operations, was forced to the end of the road to the end of the decision to study XML. This article first introduces the basic operation of XML, and then writes a frequently used XML to save the configuration file instance.

XML Common methods:

Define XML document: XmlDocument xmldoc = new XmlDocument ();

Initialize XML document: Xmldoc.load ("D:\\book.xml");//Find XML file

Create the root element: XmlElement XmlElement = Xmldoc.createelement ("", "Employees", "");

Create node: XmlElement xeSub1 = xmldoc.createelement ("title");

Find Employees node: XmlNode root = Xmldoc.selectsinglenode ("Employees");

Add node: Xe1. AppendChild (XESUB1);

Change the properties of a node: XE. SetAttribute ("Name", "Li Mingming");

Remove Xe's id attribute: Xe.removeattribute ("id");

Delete the node title:xe. RemoveChild (XE2);

1 Creating an XML document

Because it is relatively simple, direct writing methods and results.

public void Createxmldocument ()
{
XmlDocument xmldoc = new XmlDocument ();

Join the declaration paragraph of XML, <?xml version= "1.0" encoding= "gb2312"?>
XmlDeclaration xmldeclar;
Xmldeclar = Xmldoc.createxmldeclaration ("1.0", "gb2312", null);
Xmldoc.appendchild (Xmldeclar);

Add Employees root Element
XmlElement XmlElement = Xmldoc.createelement ("", "Employees", "");
Xmldoc.appendchild (xmlElement);

Adding nodes
XmlNode root = Xmldoc.selectsinglenode ("Employees");
XmlElement xe1 = xmldoc.createelement ("Node");
Xe1. SetAttribute ("Name", "Li Ming");
Xe1. SetAttribute ("ISB", "2-3631-4");

Add child nodes
XmlElement xeSub1 = xmldoc.createelement ("title");
Xesub1.innertext = "Learning vs";
Xe1. AppendChild (XESUB1);


XmlElement xeSub2 = xmldoc.createelement ("price");
Xe1. AppendChild (XESUB2);
XmlElement xeSub3 = xmldoc.createelement ("Weight");
Xesub3.innertext = "20";
Xesub2.appendchild (XESUB3);


Root. AppendChild (XE1);
Xmldoc.save ("D:\\book.xml");//Path to save
}

Results:

<?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 adding nodes

XmlDocument xmldoc = new XmlDocument ();
Xmldoc.load ("D:\\book.xml");//Find XML file
XmlNode root = Xmldoc.selectsinglenode ("Employees");//Find Employees node
XmlElement xe1 = xmldoc.createelement ("Node2");//Add Node2 node
Xe1. SetAttribute ("Name", "Zhang San");
XmlElement xeSub1 = xmldoc.createelement ("title");//define child nodes
Xesub1.innertext = "good mood";
Xe1. AppendChild (XESUB1);//Add node to Node2
Root. AppendChild (XE1);//Add node to employees
Xmldoc.save ("D:\\book.xml");

Results:

<?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 Modifying nodes:

public void Modifynode ()
{
XmlDocument XmlDocument = new XmlDocument ();
XmlDocument.Load ("D:\\book.xml");

XmlNodeList nodeList = Xmldocument.selectsinglenode ("Employees"). childnodes;//get all child nodes of the Employees node

foreach (XmlNode xn in nodeList)//traversal
{
XmlElement XE = (XmlElement) xn;
if (XE. GetAttribute ("Name") = = = "Li Ming")
{
Xe. SetAttribute ("Name", "Li Mingming");//Change the properties of a node

XmlNodeList XNL = Xe. childnodes;//get all the child nodes of XE
foreach (XmlNode xn1 in XNL)
{
XmlElement Xe2 = (XmlElement) xn1;//convert the properties of the node xn1 to XmlElement
if (Xe2. Name = = "title")//Find node with node name title
{
Xe2. InnerText = "bad weather Today";
}

if (Xe2. Name = = "Price")
{
XmlNodeList XNL2 = Xe2. ChildNodes;
foreach (XmlNode xn2 in XNL2)
{
if (xn2. Name = = "Weight")
{
Xn2. InnerText = "88";
}
}
}
}
}
}

Xmldocument.save ("D:\\book2.xml");
}

Result

<?xml version= "1.0" encoding= "GB2312"?>
-<employees>
-<node isb= "2-3631-4" Name= "Li mingming" >
<title> bad weather today </title>-<price>
<weight>88</weight>
</price>
</Node>
-<node2 name= "Zhang San" >
<title> Good Mood </title>
</Node2></Employees>

4 Deleting a node:

public void Modifynode ()
{
XmlDocument XmlDocument = new XmlDocument ();
XmlDocument.Load ("D:\\book.xml");

XmlNodeList nodeList = Xmldocument.selectsinglenode ("Employees"). childnodes;//get all child nodes of the Employees node

foreach (XmlNode xn in nodeList)//traversal
{
XmlElement XE = (XmlElement) xn;
if (XE. GetAttribute ("Name") = = = "Li Ming")
{
Xe. SetAttribute ("Name", "Li Mingming");//Change the properties of a node

XmlNodeList XNL = Xe. childnodes;//get all the child nodes of XE
foreach (XmlNode xn1 in XNL)
{
XmlElement Xe2 = (XmlElement) xn1;//convert the properties of the node xn1 to XmlElement
if (Xe2. Name = = "title")//Find node with node name title
{
Xe2. InnerText = "bad weather Today";
}

if (Xe2. Name = = "Price")
{
XmlNodeList XNL2 = Xe2. ChildNodes;
foreach (XmlNode xn2 in XNL2)
{
if (xn2. Name = = "Weight")
{
Xn2. InnerText = "88";
}
}
}
}
}
}

Xmldocument.save ("D:\\book2.xml");
}

Result

<?xml version= "1.0" encoding= "GB2312"?>
-<employees>
-<node isb= "2-3631-4" Name= "Li mingming" >
<title> bad weather today </title>-<price>
<weight>88</weight>
</price>
</Node>
-<node2 name= "Zhang San" >
<title> Good Mood </title>
</Node2></Employees>


This article describes the creation of XML, the addition of nodes, the modification and deletion of nodes, and a small example of how to save a project configuration file.

To illustrate:

First create an XML document in the project file:

<?xml version= "1.0" encoding= "Utf-8"?>
<configurationN>
<ServerAddress>1143</ServerAddress>
<ID>192.168</ID>
</configurationN>

When saving the configuration file, the main use of the two methods: Load and save.

Load: Initializes the XML document so that the project file gets the value of the specific XML node.

public void Load (string path)        {            try            {                XmlDocument XmlDocument = new XmlDocument ();                XmlDocument.Load (path);                XmlNodeList xnl = Xmldocument.selectsinglenode (Managernode). ChildNodes;                foreach (XmlNode xn in xnl)                {                    if (xn. Name = = configuration_serveraddress)                    {                        serveraddress = xn. InnerText            ;            }}} catch (Exception ex)            {}        }

Save: After modifying the profile value in the project system, the XML needs to be re-saved

public void Save (string path)        {            try            {                XmlDocument XmlDocument = new XmlDocument ();                XmlDocument.Load (path);                XmlNodeList xnl = Xmldocument.selectsinglenode (Managernode). ChildNodes;                foreach (XmlNode xn in xnl)                {                    if (xn. Name = = configuration_serveraddress)                    {                        xn. InnerText = serveraddress;                    }                }                Xmldocument.save (path);            }            catch (Exception ex)            {}        }


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

Class Configurationmanager:inotifypropertychanged {Public Const string managernode = "Configurationn";//Root node        Public Const string configuration_serveraddress = "serveraddress";//child node private string _serveraddress;            public string ServerAddress {get {return _serveraddress;}                set {_serveraddress = value;            Notifypropertychanged ("serveraddress"); }} public void Load (string path) {try {XmlDocument xmldocumen                t = new XmlDocument ();                XmlDocument.Load (path); XmlNodeList xnl = Xmldocument.selectsinglenode (Managernode).                ChildNodes; foreach (XmlNode xn in xnl) {if (xn. Name = = configuration_serveraddress) {serveraddress = xn.                    InnerText; }}} catch (Exception ex) {}} public void Save (string path) {try {Xml                Document xmlDocument = new XmlDocument ();                XmlDocument.Load (path); XmlNodeList xnl = Xmldocument.selectsinglenode (Managernode).                ChildNodes; foreach (XmlNode xn in xnl) {if (xn. Name = = configuration_serveraddress) {xn.                    InnerText = serveraddress;            }} xmldocument.save (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.tb1.Text = ConfigurationManager.Instance.ServerAddress.ToString ();        } private String path = "Config\\system.xml"; private void Button1_Click (object sender, RoutedEventArgs e) {ConfigurationManager.Instance.ServerAddre            SS = This.tb1.Text;        ConfigurationManager.Instance.Save (path);        } private void Button2_Click (object sender, RoutedEventArgs e) {Application.Current.Shutdown ();        } private void Start () {ConfigurationManager.Instance.Load (path); }    }
Class Configurationmanager:inotifypropertychanged {Public Const string managernode = "Configurationn";//Root node        Public Const string configuration_serveraddress = "serveraddress";//child node private string _serveraddress;            public string ServerAddress {get {return _serveraddress;}                set {_serveraddress = value;            Notifypropertychanged ("serveraddress"); }} public void Load (string path) {try {XmlDocument xmldocumen                t = new XmlDocument ();                XmlDocument.Load (path); XmlNodeList xnl = Xmldocument.selectsinglenode (Managernode).                ChildNodes; foreach (XmlNode xn in xnl) {if (xn. Name = = configuration_serveraddress) {serveraddress = xn.                    InnerText; }}} catch (Exception ex) {}} public void Save (string path) {try {Xml                Document xmlDocument = new XmlDocument ();                XmlDocument.Load (path); XmlNodeList xnl = Xmldocument.selectsinglenode (Managernode).                ChildNodes; foreach (XmlNode xn in xnl) {if (xn. Name = = configuration_serveraddress) {xn.                    InnerText = serveraddress;            }} xmldocument.save (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.tb1.Text = ConfigurationManager.Instance.ServerAddress.ToString ();        } private String path = "Config\\system.xml"; private void Button1_Click (object sender, RoutedEventArgs e) {ConfigurationManager.Instance.ServerAddre            SS = This.tb1.Text;        ConfigurationManager.Instance.Save (path);        } private void Button2_Click (object sender, RoutedEventArgs e) {Application.Current.Shutdown ();        } private void Start () {ConfigurationManager.Instance.Load (path); }    }

XML basic operations and save configuration file application instance

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.