XML: the abbreviation of extensible markup language. It is a metalanguage used to define other languages. Its predecessor is SGML (Standard Generalized Markup Language, standard General Markup Language ). It does not have a tag set or grammatical rule, but it has syntax rule ). Any XML document must be well-formed for any type of applications and correct parsing, that is, each opened tag must have a matched end tag, do not include tags in reverse order, and the statement composition should comply with the technical specifications. XML documents can be valid, but they are not necessarily required. A valid document is a document that complies with the document type definition (DTD. If a document complies with a schema, this document is Schema
Valid )".
Skelta BPM. Net (the world's first. net workflow engine) |
Visual Webgui (perfect user interface solution) |
List & Label (Chart report generation control) |
Dxperience Uni premium platinum edition (huidu exclusive) |
XML files are easy to process in terms of storage, exchange, and transmission of data information. This article focuses on how to use C # to perform basic operations on XML files, such: create an XML file, add, delete, modify, and query XML node information. The methods used are very basic and easy to understand (only for your own learning and memory, but also hope to bring you some help. If there is anything inappropriate, you are welcome to criticize and correct them ).
The main modules in this article are:
①: Generate an XML file
②: Traverse the node information of the XML file
③: Modify the node information of the XML file
④: Add node information to the XML file
⑤: Delete the node information of the specified XML file
Suppose we need to design such an XML file to store the corresponding information, as shown below:
<Computers>
<Computer ID = "11111111" Description = "Made in China">
<Name> Lenovo </Name>
<Price> 5000 </price>
</Computer>
<Computer ID = "2222222" Description = "Made in USA">
<Name> IBM </Name>
<Price> 10000 </price>
</Computer>
</Computers>
So how to generate this XML file? How can I read the node information of this XML file and perform operations on the node information of this XML file? See the following sample code:
[Note: because we need to use XML-related syntax and methods, we must introduce the namespace system. xml]
1 using system;
2 using system. Collections. Generic;
3 using system. LINQ;
4 using system. text;
5 using system. xml;
6
7 namespace operatexml
8 {
9 class Program
10 {
11 static void main (string [] ARGs)
12 {
13 try
14 {
15 // XML file storage path
16 string myxmlfilepath = "E: \ mycomputers. xml ";
17 // generate an XML file
18 generatexmlfile (myxmlfilepath );
19 // traverse XML file information
20 getxmlinformation (myxmlfilepath );
21 // modify the XML file information
22 modifyxmlinformation (myxmlfilepath );
23 // Add node information to the XML file
24 addxmlinformation (myxmlfilepath );
25 // Delete the specified node Information
26 deletexmlinformation (myxmlfilepath );
27}
28 catch (exception ex)
29 {
30 console. writeline (ex. tostring ());
31}
32}
33
34 Private Static void generatexmlfile (string xmlfilepath)
35 {
36 try
37 {
38 // Initialize an XML instance
39 xmldocument myxmldoc = new xmldocument ();
40 // create the XML Root Node
41 xmlelement rootelement = myxmldoc. createelement ("computers ");
42 // Add the root node to the XML file (appendchild)
43 myxmldoc. appendchild (rootelement );
44
45 // initialize the first subnode of the first layer
46 xmlelement firstlevelelement1 = myxmldoc. createelement ("computer ");
47 // fill in the attribute value (setattribute) of the first child node of the first layer)
48 firstlevelelement1.setattribute ("ID", "11111111 ");
49 firstlevelelement1.setattribute ("Description", "Made in China ");
50 // Add the first child node of the first layer to the root node
51 rootelement. appendchild (firstlevelelement1 );
52 // initialize the first subnode of the second layer
53 xmlelement secondlevelelement11 = myxmldoc. createelement ("name ");
54 // fill in the value of the first subnode of the second layer (innertext)
55 secondlevelelement11.innertext = "Lenovo ";
56 firstlevelelement1.appendchild (secondlevelelement11 );
57 xmlelement secondlevelelement12 = myxmldoc. createelement ("price ");
58 secondlevelelement12.innertext = "5000 ";
59 firstlevelelement1.appendchild (secondlevelelement12 );
60
61
62 xmlelement firstlevelelement2 = myxmldoc. createelement ("computer ");
63 firstlevelelement2.setattributes ("ID", "2222222 ");
64 firstlevelelement2.setattribute ("Description", "Made in USA ");
65 rootelement. appendchild (firstlevelelement2 );
66 xmlelement secondlevelelement21 = myxmldoc. createelement ("name ");
67 secondlevelelement21.innertext = "IBM ";
68 firstlevelelement2.appendchild (secondlevelelement21 );
69 xmlelement secondlevelelement22 = myxmldoc. createelement ("price ");
70 secondlevelelement22.innertext = "10000 ";
71 firstlevelelement2.appendchild (secondlevelelement22 );
72
73 // Save the XML file to the specified path
74 myxmldoc. Save (xmlfilepath );
75}
76 catch (exception ex)
77 {
78 console. writeline (ex. tostring ());
79}
80}
81
82 Private Static void getxmlinformation (string xmlfilepath)
83 {
84 try
85 {
86 // Initialize an XML instance
87 xmldocument myxmldoc = new xmldocument ();
88 // load the XML file (the parameter is the path of the XML file)
89 myxmldoc. Load (xmlfilepath );
90 // obtain the first node with a name match (selectsinglenode): Root Node of the XML file
91 xmlnode rootnode = myxmldoc. selectsinglenode ("computers ");
92 // obtain the innerxml and outerxml information of the node respectively.
93 string innerxmlinfo = rootnode. innerxml. tostring ();
94 string outerxmlinfo = rootnode. outerxml. tostring ();
95 // obtain the subnode of the node (that is, the first subnode of the node)
96 xmlnodelist firstlevelnodelist = rootnode. childnodes;
97 foreach (xmlnode node in firstlevelnodelist)
98 {
99 // obtain the attribute set of the node
100 xmlattributecollection attributecol = node. attributes;
101 foreach (xmlattribute attri in attributecol)
102 {
103 // obtain the attribute name and attribute value
104 string name = attrio. Name;
105 string value = attri. value;
106 console. writeline ("{0 }={ 1}", name, value );
107}
108
109 // determine whether the node has subnodes
110 if (node. haschildnodes)
111 {
112 // obtain the first subnode of the node
113 xmlnode secondlevelnode1 = node. firstchild;
114 // obtain the node name
115 string name = secondlevelnode1.name;
116 // obtain the value of the node (I .e., innertext)
117 string innertext = secondlevelnode1.innertext;
118 console. writeline ("{0 }={ 1}", name, innertext );
119
120 // obtain the second subnode of the node (obtained by array subscript)
121 xmlnode secondlevelnode2 = node. childnodes [1];
122 name = secondlevelnode2.name;
123 innertext = secondlevelnode2.innertext;
124 console. writeline ("{0 }={ 1}", name, innertext );
125}
126}
127}
128 catch (exception ex)
129 {
130 console. writeline (ex. tostring ());
131}
132}
133
134 Private Static void modifyxmlinformation (string xmlfilepath)
135 {
136 try
137 {
138 xmldocument myxmldoc = new xmldocument ();
139 myxmldoc. Load (xmlfilepath );
140 xmlnode rootnode = myxmldoc. firstchild;
141 xmlnodelist firstlevelnodelist = rootnode. childnodes;
142 foreach (xmlnode node in firstlevelnodelist)
143 {
144 // modify the attribute value of this node
145 If (node. attributes ["Description"]. value. Equals ("Made in USA "))
146 {
147 node. attributes ["Description"]. value = "Made in Hongkong ";
148}
149}
150 // to make changes to the XML file take effect, you must execute the following save Method
151 myxmldoc. Save (xmlfilepath );
152}
153 catch (exception ex)
154 {
155 console. writeline (ex. tostring ());
156}
157
158}
159
160 Private Static void addxmlinformation (string xmlfilepath)
161 {
162 try
163 {
164 xmldocument myxmldoc = new xmldocument ();
165 myxmldoc. Load (xmlfilepath );
166 // Add a node with attributes
167 foreach (xmlnode node in myxmldoc. firstchild. childnodes)
168 {
169 xmlelement newelement = myxmldoc. createelement ("color ");
170 newelement. innertext = "black ";
171 newelement. setattribute ("ismixed", "yes ");
172 node. appendchild (newelement );
173}
174 // save changes
175 myxmldoc. Save (xmlfilepath );
176}
177 catch (exception ex)
178 {
179 console. writeline (ex. tostring ());
180}
181}
182
183 Private Static void deletexmlinformation (string xmlfilepath)
184 {
185 try
186 {
187 xmldocument myxmldoc = new xmldocument ();
188 myxmldoc. Load (xmlfilepath );
189 foreach (xmlnode node in myxmldoc. firstchild. childnodes)
190 {
191 // record the last subnode under the node (Abbreviation: Last subnode)
192 xmlnode lastnode = node. lastchild;
193 // Delete the Left and Right subnodes under the last subnode
194 lastnode. removeall ();
195 // Delete the last child node
196 node. removechild (lastnode );
197}
198 // Save the modifications made to the XML file
199 myxmldoc. Save (xmlfilepath );
200}
201 catch (exception ex)
202 {
203 console. writeline (ex. tostring ());
204}
205}
206}
207}
208
In the above example, we first created the expected XML file on the E disk using the generatexmlfile method, and then read the information of the generated XML file using the getxmlinformation method; then, modify the XML file information by using the modifyxmlinformation method (<computer ID = "2222222" Description = "Made in USA">
Changed to <computer ID = "2222222" Description = "Made in Hongkong">). Then, a color node with attribute values is added to the XML file using the addxmlinformation method; finally, delete the added color node by using the deletexmlinformation method. This completes the basic operations on XML files: creating, reading, modifying, adding, and deleting.
[NOTE 1: to make any changes to the XML file take effect, you must call the Save method. Otherwise, the changes we make will not be saved]
[NOTE 2: We use xmlelement when creating a node, but read the node information with xmlnode. Here we emphasize that xmlelement is the inheritance of xmlnode, more methods can be called.
Implement the required functions]
Finally, we will summarize the basic methods for XML operations in a simple and concentrated manner, as shown below:
// The namespace to be added
Using system. xml;
// Initialize an XML instance
Xmldocument xml = new xmldocument ();
// Import the specified XML file
XML. Load ("XML file path ");
// Specify a node
Xmlnode root = xml. selectsinglenode ("node name ");
// Obtain all direct subnodes under a node
Xmlnodelist childlist = root. childnodes;
// Determine whether a subnode exists under the node
Root. haschildnodes;
// Obtain the set of nodes with the same name as the peer node
Xmlnodelist nodelist = xml. selectnodes ("node name ");
// Generate a new node
Xmlelement node = xml. createelement ("node name ");
// Add a node to a specified node as its subnode
Root. appendchild (node );
// Add the node to a subnode under the specified Node
Root. insertbefore (node, root. childenodes [I]);
// Create a property for the specified node and assign a value to it
Node. setattribute ("ID", "11111 ");
// Add a subnode to a specified Node
Root. appendchild (node );
// Obtain the specified attribute value of a specified Node
String id = node. attributes ["ID"]. value;
// Obtain the text in the specified Node
String content = node. innertext;
// Save the XML file
XML. Save ("path of XML file storage ")