Instance code sharing for basic operations in XML documents

Source: Internet
Author: User
For more information about the basic operations of XML documents, see. 1. Brief introduction

Using System. xml; // Initialize an xml instance XmlDocument xml = new XmlDocument (); // import the specified xml file xml. load (path); xml. load (HttpContext. current. server. mapPath ("~ /File/bookstore. xml "); // specify a node XmlNode root = xml. selectSingleNode ("/root"); // Obtain all direct subnodes under the node XmlNodeList childlist = root. childNodes; // determines whether a subnode root exists under the node. hasChildNodes; // obtains the XmlNodeList nodelist = xml. selectNodes ("/Root/News"); // generate a new node XmlElement node = xml. createElement ("News"); // add the node to the specified node as its root node. appendChild (node); // add the node to the root before a subnode under the specified node. insertBefore (node, root. childeNodes [I]); // creates a new attribute for the specified node and assigns a value to the node. setA Ttribute ("id", "11111"); // add the sub-node root for the specified node. appendChild (node); // Obtain the specified attribute value of the specified node string id = node. attributes ["id"]. value; // Obtain the text string content = node in the specified node. innerText; // Save the XML file string path = Server. mapPath ("~ /File/bookstore. xml "); xml. Save (path); // or use: xml. Save (HttpContext. Current. Server. MapPath ("~ /File/bookstore. xml "));

How to operate XML in C #. net
Namespace to be added:

Defines several public objects: XmlDocument xmldoc; XmlNode xmlnode; XmlElement xmlelem;

1. create an xml file in the directory with the same name as the server:

Method 1:

Xmldoc = new XmlDocument (); // add the declaration section of XML,
 XmlDeclaration xmldecl; xmldecl = xmldoc. createXmlDeclaration ("1.0", "gb2312", null); xmldoc. appendChild (xmldecl); // add a root element xmlelem = xmldoc. createElement ("", "Employees", ""); xmldoc. appendChild (xmlelem); // add another element for (int I = 1; I <3; I ++) {XmlNode root = xmldoc. selectSingleNode ("Employees"); // find
 
  
XmlElement xe1 = xmldoc. CreateElement ("Node"); // create
  
   
Node xe1.SetAttribute ("genre", ""); // Set the node genre attribute xe1.SetAttribute ("ISBN", "2-3631-4 "); // Set the ISBN attribute of the node XmlElement xesub1 = xmldoc. createElement ("title"); xesub1.InnerText = "CS from getting started to proficient"; // set the text node xe1.AppendChild (xesub1); // add
   
    
XmlElement xesub2 = xmldoc in the node. createElement ("author"); xesub2.InnerText = ""; xe1.AppendChild (xesub2); XmlElement xesub3 = xmldoc. createElement ("price"); xesub3.InnerText = "58.3"; xe1.AppendChild (xesub3); root. appendChild (xe1); // add
    
     
Node} // Save the created XML document xmldoc. save (Server. mapPath ("data. xml ")); //////////////////////////////////////// //////////////////////////////////////// //////
    
   
  
 

Result: a file named data. xml is generated in the directory with the same name. The content is as follows,

 
 
  
   CS from entry to entryHou Jie
   
    
58.3
   
  
  
   CS from entry to entryHou Jie
   
    
58.3
   
  
 

Method 2:

XmlTextWriter xmlWriter; string strFilename = Server. mapPath ("data1.xml"); xmlWriter = new XmlTextWriter (strFilename, Encoding. default); // Create an xml document xmlWriter. formatting = Formatting. indented; xmlWriter. writeStartDocument (); xmlWriter. writeStartElement ("Employees"); xmlWriter. writeStartElement ("Node"); xmlWriter. writeAttributeString ("genre", "Lizan red"); xmlWriter. writeAttributeString ("ISBN", "2-3631-4"); xmlWriter. writeStartElement ("title"); xmlWriter. writeString ("CS from entry to entry"); xmlWriter. writeEndElement (); xmlWriter. writeStartElement ("author"); xmlWriter. writeString (""); xmlWriter. writeEndElement (); xmlWriter. writeStartElement ("price"); xmlWriter. writeString ("58.3"); xmlWriter. writeEndElement (); xmlWriter. writeEndElement (); xmlWriter. close (); //////////////////////////////////////// //////////////////////////////////////// //////

Result:

 
 
  
   CS from entry to entryHou Jie
   
    
58.3
   
  
 

2. add a node:

XmlDocument xmlDoc = new XmlDocument (); xmlDoc. Load (Server. MapPath ("data. xml"); XmlNode root = xmlDoc. SelectSingleNode ("Employees"); // search
 
  
XmlElement xe1 = xmlDoc. CreateElement ("Node"); // create
  
   
Node xe1.SetAttribute ("genre", "Zhang San"); // sets the node genre attribute xe1.SetAttribute ("ISBN", "1-1111-1 "); // Set the ISBN attribute of the node XmlElement xesub1 = xmlDoc. createElement ("title"); xesub1.InnerText = "C # Getting started Help"; // set the text node xe1.AppendChild (xesub1); // add
   
    
XmlElement xesub2 = xmlDoc in the node. createElement ("author"); xesub2.InnerText = ""; xe1.AppendChild (xesub2); XmlElement xesub3 = xmlDoc. createElement ("price"); xesub3.InnerText = "158.3"; xe1.AppendChild (xesub3); root. appendChild (xe1); // add
    
     
XmlDoc in the node. save (Server. mapPath ("data. xml ")); //////////////////////////////////////// //////////////////////////////////////// //////
    
   
  
 

Result: a node is added to the original xml content. the content is as follows,

 
 
  
   CS from entry to entryHou Jie
   
    
58.3
   
  
  
   CS from entry to entryHou Jie
   
    
58.3
   
  
  
   C # Getting startedMaster
   
    
158.3
   
  
 

3. modify the node value (attributes and subnodes ):

XmlDocument xmlDoc = new XmlDocument (); xmlDoc. load (Server. mapPath ("data. xml "); XmlNodeList nodeList = xmlDoc. selectSingleNode ("Employees "). childNodes; // Obtain all subnodes of the Employees node foreach (XmlNode xn in nodeList) // traverse all subnodes {XmlElement xe = (XmlElement) xn; // Convert the subnode type to the XmlElement type if (xe. getAttribute ("genre") = "zhang san") // if the genre attribute value is "zhang san" {xe. setAttribute ("genre", "update Zhangsan"); // modify this attribute to "update Zhangsan" XmlNodeList nls = xe. childN Odes; // continue to obtain the foreach (XmlNode xn1 in nls) of all the sub-nodes of xe. // traverse {XmlElement xe2 = (XmlElement) xn1; // conversion type if (xe2.Name = "author") // if {xe2.InnerText = "Yasheng" is found; // modify the content }}} xmlDoc. save (Server. mapPath ("data. xml "); // save. //////////////////////////////////////// //////////////////////////////////////// //////

Result: the information of all the original nodes is modified. the xml content is as follows,

 
 
  
   CS from entry to entryHou Jie
   
    
58.3
   
  
  
   CS from entry to entryHou Jie
   
    
58.3
   
  
  
   C # Getting startedYasheng
   
    
158.3
   
  
 

4. modify the node (adding node attributes and adding the node's self-node ):

XmlDocument xmlDoc = new XmlDocument (); xmlDoc. load (Server. mapPath ("data. xml "); XmlNodeList nodeList = xmlDoc. selectSingleNode ("Employees "). childNodes; // Obtain foreach (XmlNode xn in nodeList) {XmlElement xe = (XmlElement) xn; xe. setAttribute ("test", "111111"); XmlElement xesub = xmlDoc. createElement ("flag"); xesub. innerText = "1"; xe. appendChild (xesub);} xmlDoc. save (Server. mapPath ("data. xml ")); //////////////////////////////////////// //////////////////////////////////////// //////

Result: an attribute is added for each node, and a subnode is added as follows,

 
 
  
   CS from entry to entryHou Jie
   
    
58.3
   
   
    
1
   
  
  
   CS from entry to entryHou Jie
   
    
58.3
   
   
    
1
   
  
  
   C # Getting startedYasheng
   
    
158.3
   
   
    
1
   
  
 

5. delete an attribute in a node:

XmlDocument xmlDoc = new XmlDocument (); xmlDoc. load (Server. mapPath ("data. xml "); XmlNodeList xnl = xmlDoc. selectSingleNode ("Employees "). childNodes; foreach (XmlNode xn in xnl) {XmlElement xe = (XmlElement) xn; xe. removeAttribute ("genre"); // delete the genre attribute XmlNodeList nls = xe. childNodes; // continue to obtain the foreach (XmlNode xn1 in nls) of all the child nodes of xe // traverse {XmlElement xe2 = (XmlElement) xn1; // conversion type if (xe2.Name = "flag") // if {xe. removeChild (xe2); // delete} xmlDoc. save (Server. mapPath ("data. xml ")); //////////////////////////////////////// //////////////////////////////////////// /// //]

Result: a node attribute and a subnode of the node are deleted as follows,

 
 
  
   CS from entry to entryHou Jie
   
    
58.3
   
  
  
   CS from entry to entryHou Jie
   
    
58.3
   
  
  
   C # Getting startedYasheng
   
    
158.3
   
  
 

6. delete a node:

XmlDocument xmlDoc = new XmlDocument (); xmlDoc. load (Server. mapPath ("data. xml "); XmlNode root = xmlDoc. selectSingleNode ("Employees"); XmlNodeList xnl = xmlDoc. selectSingleNode ("Employees "). childNodes; for (int I = 0; I
 
  

Result: all nodes that meet the conditions are deleted. The original content is as follows:

   
   
    
     CS from entry to entryHou Jie
     
      
58.3
     
    
    
     CS from entry to entryHou Jie
     
      
58.3
     
    
    
     C # Getting startedMaster
     
      
158.3
     
    
    
     C # Getting startedMaster
     
      
158.3
     
    
   

Deleted content:

   
   
    
     CS from entry to entryHou Jie
     
      
58.3
     
    
    
     CS from entry to entryHou Jie
     
      
58.3
     
    
   

7. read xml based on text files

System. IO. streamReader myFile = new System. IO. streamReader (Server. mapPath ("data. xml "), System. text. encoding. default); // note System. text. encoding. defaultstring myString = myFile. readToEnd (); // myString is the read string myFile. close ();

3. Advanced Applications

/* Two xml methods for reading xml data */
   
    
Something
   
   
    
Something
   /* Method 1 */DS. readXml ("your xmlfile name"); Container. dataItem ("bb"); Container. dataItem ("cc"); DS. readXmlSchema ("your xmlfile name");/* method 2 */What should I do if I want to find 123 and get 321? Using System. XML; XmlDataDocument xmlDoc = new System. xml. xmlDataDocument (); xmlDoc. load (@ "c:/Config. xml "); XmlElement elem = xmlDoc. getElementById ("add"); string str = elem. attributes ["value"]. value/* method 3: SelectSingleNode read xml in two formats *---/--------------------------------------------------------------------
   
   
    
     
Data Source = yf; user id = ctm_dbo; password = 123
     
   Export XmlDocument doc = new XmlDocument (); doc. Load (strXmlName); XmlNode node = doc. SelectSingleNode ("/configuration/etettings/ConnectionString"); if (node! = Null) {string k1 = node. value; // nullstring k2 = node. innerText; // Data Source = yf; user id = ctm_dbo; password = 123 string k3 = node. innerXml; // Data Source = yf; user id = ctm_dbo; password = 123 node = null ;} **************************************** ****************************
   
    
   ** ---------------------------------------------------------------------- ** XmlNode node = doc. SelectSingleNode ("/configuration/deleteworkflow/add"); if (node! = Null) {string k = node. attributes ["key"]. value; string v = node. attributes ["value"]. value; node = null;} * -------------------------------------------------------------------- * XmlNode node = doc. selectSingleNode ("/configuration/appSettings/add"); if (node! = Null) {XmlNodeReader nr = new XmlNodeReader (node); nr. MoveToContent (); // check whether the current node is a content node. If this node is not a content node, the reader jumps forward to the next content node or the end of the file. Nr. MoveToAttribute ("value"); string s = nr. Value; node = null ;}

The above is the details about the instance code for the basic operations of the XML document. For more information, see other related articles in the first PHP community!

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.