A summary of xml usage

Source: Internet
Author: User
Extensible markup language, a markup language used to mark electronic documents so that they can be used to mark data and define data types, is a source language that allows you to define your own markup language. 1. understand xml

Extensible markup language, a markup language used to mark electronic documents so that they can be used to mark data and define data types, is a source language that allows you to define your own markup language.

2. differences between CAPTCHA and HyperText Markup languages

2.1 html does not need to appear in pairs, but xml must appear in pairs.

2.2 html is case-insensitive, but xml is case-insensitive.

3. add, delete, modify, and query xml documents

// Declare an empty XmlDocument object protected XmlDocument XmlDoc = new XmlDocument ();////// Constructor, import xml file //////Public XmlHelper (string path) {try {XmlDoc. Load (path) ;}catch (Exception ex) {throw ex ;}}////// Save the file //////Public void SaveXml (string path) {try {XmlDoc. Save (path) ;}catch (System. Exception ex) {throw ex ;}}
////// Obtain the content of the subnode of the node ///////////////
 Public string GetNodeChildAttribute (string path, string rootNode, string attributeName) {XmlNode xn = XmlDoc. selectSingleNode (rootNode); StringBuilder sb = new StringBuilder (); XmlNodeList xnl = xn. childNodes; foreach (XmlNode xnf in xnl) {XmlElement xe = (XmlElement) xnf; XmlNodeList xnf1 = xe. childNodes; foreach (XmlNode xn2 in xnf1) {if (xn2.Name = attributeName) {sb. append (xn2.InnerText); // displays the child node text }}return sb. toString ();}
////// Get the node attribute value //////Xml Path///Root node name///Attribute name///
 Public string GetNodeAttribute (string path, string rootNode, string attributeName) {try {XmlNode xn = XmlDoc. selectSingleNode (rootNode); XmlNodeList xnl = xn. childNodes; StringBuilder sb = new StringBuilder (); foreach (XmlNode xnf in xnl) {XmlElement xe = (XmlElement) xnf; sb. append (xe. getAttribute (attributeName);} return sb. toString () ;}catch (Exception) {throw ;}}
////// Delete node/node attributes //////Xml file address///Root node name///Node to be deleted///Node attributes///Attribute valuePublic void DeleteNode (string path, string rootNode, string attributeName, string attributeValue) {try {XmlNodeList xnl = XmlDoc. selectSingleNode (rootNode ). childNodes; foreach (XmlNode xn in xnl) {XmlElement xe = (XmlElement) xn; if (xe. getAttribute (attributeName) = attributeValue) {// xe. removeAttribute (attributeName); // delete the property xe. removeAll (); // delete all content of the node} SaveXml (path);} catch (Exception) {throw ;}}
////// Modify the subnode content of a node //////Xml file path///Root node name///Node subnode name///Original content of the subnode of the node///New content of the node's subnodePublic void UpdateChildNodeAttribute (string path, string rootNode, string attributeName, string attributeOldValue, string attributeNewValue) {try {XmlNodeList nodeList = XmlDoc. selectSingleNode (rootNode ). childNodes; // Obtain all subnodes of the root node foreach (XmlNode xn in nodeList) // traverse all subnodes {XmlElement xe = (XmlElement) xn; // Convert the subnode type to the XmlElement type if (string. isNullOrEmpty (attributeName) | string. isNullOrEmpty (attribut EOldValue) {return;} else {XmlNodeList nls = xe. ChildNodes; if (nls! = Null & nls. count> 0) {foreach (XmlNode xn1 in nls) // traverse {XmlElement xe2 = (XmlElement) xn1; // conversion type if (xe2.InnerText = attributeOldValue) // If {xe2.InnerText = attributeNewValue is found; // modify the break; // you can find and exit. }}}} SaveXml (path);} catch (Exception) {throw ;}}
////// Modify node attribute values //////Xml file path///Root node name, for example, bookstore///Node attribute name///Original node attribute value///Value after node attribute modificationPublic void UpdateNodeAttribute (string path, string rootNode, string attributeName, string attributeOldValue, string attributeNewValue) {try {XmlNodeList nodeList = XmlDoc. selectSingleNode (rootNode ). childNodes; // Obtain all subnodes of the root node foreach (XmlNode xn in nodeList) // traverse all subnodes {XmlElement xe = (XmlElement) xn; // assign the child node type to the xmlelement type if (string. isNullOrEmpty (attributeName) | string. isNullOrEmpty (attributeOldValue) {return;} else {if (xe. getAttribute (attributeName) = attributeOldValue) {xe. setAttribute (attributeName, attributeNewValue) ;}} SaveXml (path);} catch (Exception) {throw ;}}
////// Insert a node //////Xml file path///Root node name, for example, bookstore///Node name, for example, book///Node attributes-set of attribute values///Node subnode name-contentPublic void InsertNode (string path, string rootNode, string node, Dictionary
 
  
NodeAttributes, Dictionary
  
   
ChildAttributes) {try {XmlNode root = XmlDoc. selectSingleNode (rootNode); // find the root node bookstore XmlElement xe1 = XmlDoc. createElement (node); // Create a subnode book if (nodeAttributes! = Null & nodeAttributes. Count> 0) {foreach (var n in nodeAttributes) {xe1.SetAttribute (n. Key, n. Value) ;}} if (childAttributes! = Null & childAttributes. count> 0) {XmlElement xesub1; foreach (var n in childAttributes) {xesub1 = XmlDoc. createElement (n. key); xesub1.InnerText = n. value; xe1.AppendChild (xesub1); // add
   
    
Node} root. AppendChild (xe1); SaveXml (path);} catch (Exception) {throw ;}}
   
  
 

Call:

String path = Server. MapPath ("Books. xml"); XmlHelper xHelper = new XmlHelper (path);/* insert * // Dictionary
 
  
Dc1 = new Dictionary
  
   
(); // Dc1.Add ("genre", ""); // dc1.Add ("ISBN", "2-3631-4"); // Dictionary
   
    
Dc2 = new Dictionary
    
     
(); // Dc2.Add ("title", "CS from getting started to proficient"); // dc2.Add ("author", ""); // dc2.Add ("price", "58.3"); // xHelper. insertNode (path, "bookstore", "book", dc1, dc2);/* modify * // xHelper. updateNodeAttribute (path, "bookstore", "genre", "Li zanhong", "Li"); // xHelper. updateChildNodeAttribute (path, "bookstore", "title", "CS from entry to entry", "cs");/* delete node * // xHelper. deleteNode (path, "bookstore", "genre", "Li"); // Response. write (xHelper. getNodeAttribute (path, "bookstore", "genre"); // Response. write (xHelper. getNodeChildAttribute (path, "bookstore", "price "));
    
   
  
 

4. bind data through xml

Xml to able

public DataTable XmlToData(string path, string rootNode, params string[] columns)       {           DataTable dt = new DataTable();           XmlNodeList xn = XmlDoc.SelectSingleNode(rootNode).ChildNodes;           try           {               if (columns.Length > 0)               {                   DataColumn dc;                   for (int i = 0; i < columns.Length; i++)                   {                       dc = new DataColumn(columns[i]);                       dt.Columns.Add(dc);                   }                   foreach (XmlNode xnf in xn)                   {                       XmlElement xe = (XmlElement)xnf;                       XmlNodeList xnf1 = xe.ChildNodes;                       int i = 0;                       DataRow dr = dt.NewRow();                       foreach (XmlNode xn2 in xnf1)                       {                           dr[i] = xn2.InnerText;                           i++;                       }                       dt.Rows.Add(dr);                   }               }           }           catch (Exception)           {                throw;           }           return dt;        }

Call:

//string[] arr = { "title", "author", "price" };           //GridView1.DataSource = xHelper.XmlToData(path, "bookstore", arr);           //GridView1.DataBind();

DataTable to xml

/* Datatable to convert xml */public string DataTableToXml (DataTable dt) {if (dt! = Null) {MemoryStream ms = null; XmlTextWriter XmlWt = null; try {ms = new MemoryStream (); // instantiate XmlWt = new XmlTextWriter (ms, Encoding. unicode); // obtain the data dt in ds. writeXml (XmlWt); int count = (int) ms. length; byte [] temp = new byte [count]; ms. seek (0, SeekOrigin. begin); ms. read (temp, 0, count); // returns the Unicode encoded text UnicodeEncoding ucode = new UnicodeEncoding (); string returnValue = ucode. getStrin G (temp). Trim (); return returnValue;} catch (System. Exception ex) {throw ex;} finally {// release the resource if (XmlWt! = Null) {XmlWt. Close (); ms. Close (); ms. Dispose () ;}} else {return "";}}

Call:

//bool s = xHelper.CDataToXmlFile(xHelper.XmlToData(path, "bookstore", arr), "Bookss.xml","book");

5. xml serialization and deserialization

[Serializable]   public class Person   {       public string Name { get; set; }       public int Age { get; set; }   }
public class CXmlSerializer
 
   where T : new()    {        private static XmlSerializer _Serializer = new XmlSerializer(typeof(T));         public static string Serialize(T t)        {            string s = "";            using (MemoryStream ms = new MemoryStream())            {                _Serializer.Serialize(ms, t);                s = System.Text.UTF8Encoding.UTF8.GetString(ms.ToArray());            }            return s;        }         public static T Deserialize(string s)        {            T t;            using (MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(s)))            {                t = (T)_Serializer.Deserialize(ms);            }            return t;        }    }
 

Call:

List
 
   list = new List
  
    { new Person { Name = "Xuj", Age = 20 }, new Person { Name = "duj", Age = 20 }, new Person { Name = "fuj", Age = 20 } };            string s = CXmlSerializer
   
    >.Serialize(list);
   
  
 

The above is a detailed summary of the use of xml. 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.