. NET operations XML file (Add. Modify, delete, read) __.net

Source: Internet
Author: User
Tags httpcontext
 There is a requirement today to manipulate an XML node. Suddenly see a lot of forgotten. The internet has read some information. The head is really not enough. I'll share the information I found here. This article belongs to the net pick/
1  first, Brief introduction 2 using system.xml;
3 //Initializes an XML instance 4 xmldocument xml=new xmldocument (); 5 //Import the specified XML file 6 xml.
Load (path); 7 xml.
Load (HttpContext.Current.Server.MapPath ("~/file/bookstore.xml")); 8 //Specifies a node 9 xmlnode root=xml.
selectSingleNode ("/root"); 10 //gets all the direct child nodes under the node 11 xmlnodelist childlist=root.
ChildNodes; 12 //determine if there is a child node under the node 13 root.
HasChildNodes; 14 //gets the same sibling node collection 15 xmlnodelist nodelist=xml with the same name.
SelectNodes ("/root/news");
16 //generates a new node 17 xmlelement node=xml.createelement_x ("News"); 18 //the node to the specified node as its child node 19 root.
AppendChild (node); 20 //adds a node to 21 root before a child node under the specified node. InsertBefore (Node,root.
Childenodes[i]); 22 //the new attribute for the specified node and assigns a 23 node value.
SetAttribute ("id", "11111"); 24 //adds a child node 25 root to the specified node.
AppendChild (node); 26 //gets the specified property value 27 string id=node for the specified node. attributes["id"].
Value; 28 //gets the text 29 string content=node in the specified node.
InnerText; 30 //Save XML file 31 string path=server.mappath ("~/file/bookstore.xml"); 32 xml.
Save (path); 33 //or Use:xml. Save (HttpContext.Current.Server.MapPath ("~/file/bookstore.xml"));  34  II, concrete instance 35  how to manipulate XML 36 in C#.net
  Namespaces to add: 37 using system.xml;
38  defines several common objects: 39 xmldocument xmldoc;
40 xmlnode XmlNode;
41 xmlelement Xmlelem;
42 1, create an XML file to the server directory with the same name: 43  44  method One: 45 xmldoc = new xmldocument ();
46 //joins the declaration paragraph of XML, <?xml version= "1.0" encoding= "gb2312"?> 47 xmldeclaration; 48 xmldecl = xmldoc.
Createxmldeclaration ("1.0", "gb2312", null); 49 xmldoc.
AppendChild (XMLDECL); 50 //Add a root element 51 xmlelem = xmldoc.createelement_x (  ""  ,  "Employees"  ,  " )
; 52 xmldoc.
AppendChild (Xmlelem); 53 //adds another element 54 for (int i=1;i<3;i++) 55 {56 xmlnode Root=xmldoc. selectSingleNode ("Employees")/Find <Employees>  57 xmlelement xe1=xMldoc.createelement_x ("node");//Create a <Node> node   58 xe1. SetAttribute ("Genre", "Li Zhanhong");/set the node genre properties   59 xe1. SetAttribute ("ISBN", "2-3631-4");/set this node ISBN property 60 xmlelement xesub1=xmldoc.createelement_x ("title");  61  xesub1. Innertext= "CS from entry to Mastery";/Set text node   62&NBSP;XE1.
AppendChild (XESUB1);//Add to <Node> node   63 xmlelement xesub2=xmldoc.createelement_x ("author");  64 xesub2. innertext= "Hou Jie";  65 xe1. AppendChild (XESUB2);  66 xmlelement xesub3=xmldoc.createelement_x ("price");  67 xesub3. innertext= "58.3";  68 xe1.
AppendChild (XESUB3); 69 root. AppendChild (XE1);//Add to <Employees> node   70&NBSP} 71 //Save the created XML document 72 xmldoc.
Save (Server.MapPath ("Data.xml")); 73//////////////////////////////////////////////////////////////////////////////////////74  Results: A file named Data.xml was generated under the same directory, with the following contents, 75 <?xml version= "1.0"  encoding= "gb2312"?> 76 <employees > 77 &Lt Node genre= "Li Zhanhong"  isbn= "2-3631-4" > 78 <title>cs from Entry to Mastery </title> 79 <author> Hou Jie </author> 80 <price>58.3</price> 81 </node> 82 <node genre= "李赞红"   isbn= "2-3631-4" > 83 <title>cs from entry to proficiency </title> 84 <author> Hou Jie </author> 85  <price>58.3</price> 86 </node> 87 </employees> 88  89  Method II: 90 
xmltextwriter xmlwriter;
91 string strfilename = Server.MapPath ("Data1.xml"); 92 xmlwriter = new xmltextwriter (Strfilename,encoding.default);//Create an XML document 93 
xmlwriter.formatting = formatting.indented;
94 xmlwriter.writestartdocument ();
95 xmlwriter.writestartelement ("Employees");
96 xmlwriter.writestartelement ("Node");
97 xmlwriter.writeattributestring ("Genre", "Li Zhanhong");
98 xmlwriter.writeattributestring ("ISBN", "2-3631-4");
99 xmlwriter.writestartelement ("title"); 100 xmlwriter.wrItestring ("CS from Introduction to proficiency");
101 xmlwriter.writeendelement ();
102 xmlwriter.writestartelement ("author");
103 xmlwriter.writestring ("Hou Jie");
104 xmlwriter.writeendelement ();
105 xmlwriter.writestartelement ("Price");
106 xmlwriter.writestring ("58.3");
107 xmlwriter.writeendelement ();
108 xmlwriter.writeendelement ();
109 xmlwriter.close (); 110//////////////////////////////////////////////////////////////////////////////////////111  Results: 112  <?xml version= "1.0"  encoding= "gb2312"?> 113 <employees> 114 <node genre= "李赞红"   isbn= "2-3631-4" > 115 <title>cs from entry to proficiency </title> 116 <author> Hou Jie </author> 117  <price>58.3</price> 118 </node> 119 </employees> 120 2, add a node: 121
 xmldocument xmldoc=new xmldocument ();  122 xmldoc.load (Server.MapPath ("Data.xml"));  123 xmlnode Root=xmldoc.selectsinglenode ("Employees");/Find <employees>  124 xmlelement xe1=xmldoc.createelement_x ("node");//Create a <Node> node   125&NBSP;XE1 . SetAttribute ("Genre", "John");/set the node genre properties   126 xe1. SetAttribute ("ISBN", "1-1111-1");/set the Node ISBN property 127 xmlelement xesub1=xmldoc.createelement_x ("title");   128&NBSP;XESUB1. Innertext= "C # Getting Started help";//Setting up text nodes   129 xe1. AppendChild (XESUB1);//Add to <Node> node   130 xmlelement xesub2=xmldoc.createelement_x ("author");   131&NBSP;XESUB2. innertext= "Master";  132 xe1. AppendChild (XESUB2);  133 xmlelement xesub3=xmldoc.createelement_x ("price");  134 xesub3. innertext= "158.3";  135 xe1.
AppendChild (XESUB3); 136 root.
AppendChild (XE1);//Add to <Employees> node   137 xmldoc.save (Server.MapPath ("Data.xml")); 138//////////////////////////////////////////////////////////////////////////////////////139  Results: A node is added to the original content of XML, and the contents are as follows, 140 <?xml version= "1.0"  encoding= "gb2312"?> 141 &Lt
employees> 142 <node genre= "Li Zhanhong"  isbn= "2-3631-4" > 143 <title>cs from Getting started to mastering </title> 144 <author> </author> 145 <price>58.3</price> 146 </node> 147  <node genre= "Li Zhanhong"  isbn= "2-3631-4" > 148 <title>cs from Entry to Mastery </title> 149 < author> </author> 150 <price>58.3</price> 151 </node> 152 <node Genre= "John"  isbn= "1-1111-1" > 153 <title>c# Introductory Help </title> 154 <author> master </ author> 155 <price>158.3</price> 156 </node> 157 </employees> 158  3, modify the node values (attributes and child nodes): 159 xmldocument xmldoc=new xmldocument ();  160 xmldoc.load (Server.MapPath ("
Data.xml ")); 161 xmlnodelist Nodelist=xmldoc.selectsinglenode ("Employees"). childnodes;//gets all child nodes of the Employees node 162 foreach (XmlNode xn in nodelist)//traverses all child nodes   163 {   164 xmlelement XE= (XmlElement) xn;//Converts a child node type to a XmlElement type   165 if (XE. GetAttribute ("genre") = = "John")//If genre property value is "John"   166 {  167 xe. SetAttribute ("Genre", "Update John");//Modify this property to "update John" 168 xmlnodelist Nls=xe. CHILDNODES;//continues to fetch all child nodes of the XE child node   169 foreach (XmlNode xn1 in nls)/traversal   170 {  171  xmlelement xe2= (XmlElement) xn1;//conversion type   172&NBSP;IF (xe2. name== "Author")//If found   173 {  174 xe2. innertext= "Ya sheng";//Modify 175 }  176 }  177 }  178 }  179 xmldoc.save (
Server.MapPath ("Data.xml"))//save. 180//////////////////////////////////////////////////////////////////////////////////////181  Result: The information of all the original nodes has been modified, the contents of XML are as follows, 182 <?xml version= "1.0"  encoding= "gb2312"?> 183 <employees > 184 <node genre= "Li Zhanhong"  isbn= "2-3631-4" > 185 <title>cs from Getting Started to mastering </title> 186  <author> Hou Jie </author> 187 <price>58.3</price> 188 </node> 189 <node genre= "Li Zhanhong"  isbn= "2-3631-4" > 190 <title>cs from entry to Mastery </ title> 191 <author> </author> 192 <price>58.3</price> 193 </node > 194 <node genre= "Update John"  isbn= "1-1111-1" > 195 <title>c# Getting Started help </title> 196  <author> Asia wins </author> 197 <price>158.3</price> 198 </node> 199 
</Employees> 200 4, modify the node (Add node properties and add nodes from the node): 201 xmldocument xmldoc=new xmldocument (); 
202 xmldoc.load (Server.MapPath ("Data.xml")); 203 xmlnodelist Nodelist=xmldoc.selectsinglenode ("Employees"). childnodes;//gets all the subnodes of the Employees Node 204 foreach (XmlNode xn in nodelist)   205 {  206  xmlelement xe= (XmlElement) xn;  207 xe.
SetAttribute ("Test", "111111"); 208 xmlelement xesub=xmldoc.createelement_x ("flag");  209 xesub. innertext= "1";  210 xe. AppendChild (XESub);  211 }  212 xmldoc.save (Server.MapPath ("Data.xml")); 213//////////////////////////////////////////////////////////////////////////////////////214  Result: The attributes of each node are added one, and the child nodes are added as follows, 215 <?xml version= "1.0"  encoding= "gb2312"?> employees> 217 <node genre= "Li Zhanhong"  isbn= "2-3631-4"  test= "111111" > 218 <title> CS from getting started to proficient </title> 219 <author> </author> 220 <price>58.3</price> 221  <flag>1</flag> 222 </node> 223 <node genre= "Li Zhanhong"  isbn= "2-3631-4"   test= "111111" > 224 <title>cs from entry to proficiency </title> 225 <author> Hou Jie </author> 226  <price>58.3</price> 227 <flag>1</flag> 228 </node> 229 <node Genre = "Update John"  isbn= "1-1111-1"  test= "111111" > 230 <title>c# Getting Started help </title> 231 < Author> </author> 232 <price>158.3</price> 233 <flag>1</flag> 234 </node> 235 </Employees> 236 5, delete one of the properties in the node: 237 xmldocument xmldoc=new xmldocument ();  238 xmldoc.load ( Server.MapPath ("Data.xml"));  239 xmlnodelist xnl=xmldoc.selectsinglenode ("Employees"). childnodes;  240 foreach (XmlNode xn in xnl)   241 {  242 xmlelement xe= ( XmlElement) xn;  243 xe. RemoveAttribute ("genre");//Delete genre property 244 xmlnodelist Nls=xe. CHILDNODES;//continues to fetch all child nodes of the XE child node   245 foreach (XmlNode xn1 in nls)/traversal   246 {  247  xmlelement xe2= (XmlElement) xn1;//conversion type   248&NBSP;IF (xe2. name== "flag")//If found   249 {  250 xe. RemoveChild (XE2);//delete 251 }  252 }  253 }  254 xmldoc.save ("
Data.xml ")); 255//////////////////////////////////////////////////////////////////////////////////////] 256  Result: Delete One of the attributes of the endpoint and one of the nodesThe child node, the contents are as follows, 257 <?xml version= "1.0"  encoding= "gb2312"?> 258 <employees> 259 < Node isbn= "2-3631-4"  test= "111111" > 260 <title>cs from Getting Started to mastering </title> 261 <author> Hou Jie </author> 262 <price>58.3</price> 263 </node> 264 <node ISBN= "2-3631-4
" test=" 111111 > 265 <title>cs from entry to proficiency </title> 266 <author> Hou Jie </author> 267 <price>58.3</price> 268 </node> 269 <node ISBN= "1-1111-1"  test= " 111111 "> 270 <title>c# Getting Started help </title> 271 <author> </author> 272 < Price>158.3</price> 273 </node> 274 </employees> 275 6, delete node: 276  XmlDocument xmldoc=new xmldocument ();  277 xmldoc.load (Server.MapPath ("Data.xml"));  278
 xmlnode Root=xmldoc.selectsinglenode ("Employees"); 279 xmlnodelist Xnl=xmldoc.selectsinglenode ("Employees"). childnodes;  280 for (int i=0;i<xnl. count;i++) 281 {282 xmlelement xe= (XmlElement) xnl. Item (i);  283 if (XE. GetAttribute ("genre") = = "John")   284 {  285 root.
RemoveChild (XE); 286 if (I&LT;XNL.
Count) i=i-1;
287 }  288 } 289 xmldoc.save (Server.MapPath ("Data.xml")); 290//////////////////////////////////////////////////////////////////////////////////////] 291  Results: Delete all the nodes that match the condition, the original content: 292 <?xml version= "1.0"  encoding= "gb2312"?> 293 <employees> 294  <node genre= "Li Zhanhong"  isbn= "2-3631-4" > 295 <title>cs from Entry to Mastery </title> 296 < author> </author> 297 <price>58.3</price> 298 </node> 299 <node Genre= "Li Zhanhong"  isbn= "2-3631-4" > 300 <title>cs from entry to proficiency </title> 301 <author> Hou Jie </ author> 302 <price>58.3</price> 303 </node> 304 <node genre= "John"  ISBN= "1-1111-1" > 305 <title>c# Introductory Help </title> 306 <author> master </author> 307 < price>158.3</price> 308 </node> 309 <node genre= "John"  isbn= "1-1111-1" > 310  <title>c# Getting Started help </title> 311 <author> master </author> 312 <price>158.3< /price> 313 </node> 314 </employees> 315  deleted content: 316 <?xml version= "1.0"  encoding= "gb2312"?> 317 <employees> 318 <node genre= "Li Zhanhong"  isbn= "2-3631-4" > 319  <title>cs from getting started to proficient </title> 320 <author> </author> 321 <price>58.3 </price> 322 </node> 323 <node genre= "Li Zhanhong"  isbn= "2-3631-4" > 324 <title >cs from entry to Mastery </title> 325 <author> </author> 326 <price>58.3</price> 327  </Node> 328 </employees> 329 7, reading XML by text file 330 system.io.streamreader myFile =new  331 system.io.streamreader (Server.MapPath ("Data.xml"), System.Text.Encoding.Default); 332 //Note System.Text.Encoding.Default 333 string mystring = Myfile.readtoend ();//mystring is read out string 334
 myfile.close (); 335  336  III, advanced applications   337  338 <aaa> 339 <bb>something</bb> 340  <cc>something</cc> 341 </aaa> 342  343 <aaa> 344 <add key= "123"  value= "321"/> 345 </aaa> 346  347 ds.
READXML ("Your xmlfile name");
348 container.dataitem ("BB");
349 container.dataitem ("CC"); 350 ds.
ReadXmlSchema ("Your xmlfile name"); 351  352  353 <aaa> 354 <add key= "123"  value= "321"/> 355 </aaa> 356
  What should I write if I have to find 123 and then get 321?
357  358 using system.xml;
359 xmldatadocument xmldoc = new system.xml.xmldatadocument ();
360 xmldoc.load (@ "C:\Config.xml"); 361 xmlelement elem = Xmldoc.getelementbyid ("add"); 362 string str = Elem. attributes["Value"].
Value 363  364  365  366 --------------------------------------------------------------------
367 <?xml version= "1.0" encoding= "Utf-8"?> 368 <configuration> 369 <appsettings> 370 <connectionstring>data SOURCE=YF; User id=ctm_dbo;password=123</connectionstring>  371 </appsettings> 372 </ Configuration> 373 -----------------------

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.