search
HomeBackend DevelopmentXML/RSS TutorialA detailed introduction to the summary of how to use xml

1. Understand xml

Extensible Markup Language, a markup language used to mark electronic documents to make them result-oriented. It can be used to mark data and define data types. It is a markup language that allows users to A source language that defines its own markup language.

2. Difference from Hypertext Markup Language

2.1 HTML does not necessarily need to appear in pairs, while xml must appear in pairs.

2.2 html is not case-sensitive, but xml is.

3. Check the addition, deletion and modification of xml documents

//声明一个XmlDocument空对象
       protected XmlDocument XmlDoc = new XmlDocument();
       /// <summary>
       /// 构造函数,导入xml文件
       /// </summary>
       /// <param name="path"></param>
       public XmlHelper(string path)
       {
           try
           {
               XmlDoc.Load(path);
           }
           catch (Exception ex)
           {
               throw ex;
           }
       }
       /// <summary>
       /// 保存文件
       /// </summary>
       /// <param name="path"></param>
       public void SaveXml(string path)
       {
           try
           {
               XmlDoc.Save(path);
           }
           catch (System.Exception ex)
           {
               throw ex;
           }
       }
/// <summary>
       /// 获取节点的子节点的内容
       /// </summary>
       /// <param name="path"></param>
       /// <param name="rootNode"></param>
       /// <param name="attributeName"></param>
       /// <returns></returns>
       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);//显示子节点点文本
                   }
               }
           }
           return sb.ToString();
       }
/// <summary>
        /// 获取节点的属性值
        /// </summary>
        /// <param name="path">xml路径</param>
        /// <param name="rootNode">根节点名称</param>
        /// <param name="attributeName">属性名称</param>
        /// <returns></returns>
        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;
            }
        }
/// <summary>
       /// 删除节点/节点属性
       /// </summary>
       /// <param name="path">xml文件地址</param>
       /// <param name="rootNode">根节点名称</param>
       /// <param name="delNode">要删除的节点</param>
       /// <param name="attributeName">节点属性</param>
       /// <param name="attributeValue">属性值</param>
       public 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);//删除属性
                       xe.RemoveAll();//删除该节点的全部内容
                   }
               }
               SaveXml(path);
           }
           catch (Exception)
           {
 
               throw;
           }
       }
/// <summary>
       /// 修改节点的子节点内容
       /// </summary>
       /// <param name="path">xml文件路径</param>
       /// <param name="rootNode">根节点名称</param>
       /// <param name="attributeName">节点的子节点名称</param>
       /// <param name="attributeOldValue">节点的子节点原始内容</param>
       /// <param name="attributeNewValue">节点的子节点新内容</param>
       public void UpdateChildNodeAttribute(string path, string rootNode, string attributeName,string attributeOldValue, string attributeNewValue)
       {
           try
           {
               XmlNodeList nodeList = XmlDoc.SelectSingleNode(rootNode).ChildNodes;//获取根节点的所有子节点
               foreach (XmlNode xn in nodeList)//遍历所有子节点
               {
                   XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型
                   if (string.IsNullOrEmpty(attributeName) || string.IsNullOrEmpty(attributeOldValue))
                   {
                       return;
                   }
                   else
                   {
                       XmlNodeList nls = xe.ChildNodes;
                       if (nls != null && nls.Count > 0)
                       {
                           foreach (XmlNode xn1 in nls)//遍历
                           {
                               XmlElement xe2 = (XmlElement)xn1;//转换类型
                               if (xe2.InnerText == attributeOldValue)//如果找到
                               {
                                   xe2.InnerText = attributeNewValue;//则修改
                                   break;//找到退出来就可以了
                               }
                           }
                       }
                   }
               }
               SaveXml(path);
           }
           catch (Exception)
           {
 
               throw;
           }
       }
/// <summary>
        /// 修改节点属性值操作
        /// </summary>
        /// <param name="path">xml文件路径</param>
        /// <param name="rootNode">根节点名称,如:bookstore</param>
        /// <param name="attributeName">节点属性名</param>
        /// <param name="attributeOldValue">节点属性原来值</param>
        /// <param name="attributeNewValue">节点属性修改后的值</param>
        public void UpdateNodeAttribute(string path, string rootNode, string attributeName, string attributeOldValue, string attributeNewValue)
        {
            try
            {
                XmlNodeList nodeList = XmlDoc.SelectSingleNode(rootNode).ChildNodes;//获取根节点的所有子节点
                foreach (XmlNode xn in nodeList)//遍历所有子节点
                {
                    XmlElement xe = (XmlElement)xn;//将子节点类型专程xmlelement类型
                    if (string.IsNullOrEmpty(attributeName) || string.IsNullOrEmpty(attributeOldValue))
                    {
                        return;
                    }
                    else
                    {
                        if (xe.GetAttribute(attributeName) == attributeOldValue)
                        {
                            xe.SetAttribute(attributeName, attributeNewValue);
                        }
                    }
                }
                SaveXml(path);
            }
            catch (Exception)
            {
 
                throw;
            }
        }
/// <summary>
        /// 插入节点操作
        /// </summary>
        /// <param name="path">xml文件路径</param>
        /// <param name="rootNode">根节点名称,如:bookstore</param>
        /// <param name="node">节点名称,如:book</param>
        /// <param name="nodeAttributes">节点的属性-属性值集合</param>
        /// <param name="childAttributes">节点子节点名称-内容</param>
        public void InsertNode(string path, string rootNode, string node, Dictionary
        <string, string> nodeAttributes, Dictionary<string, string> childAttributes)
        {
            try
            {
                XmlNode root = XmlDoc.SelectSingleNode(rootNode);//找到根节点bookstore
                XmlElement xe1 = XmlDoc.CreateElement(node);//创建子节点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);//添加到<book>节点中
                    }
                }
                root.AppendChild(xe1);
                SaveXml(path);
            }
            catch (Exception)
            {
 
                throw;
            }
        }

Call:

string path = Server.MapPath("Books.xml");
           XmlHelper xHelper = new XmlHelper(path);
           /*插入*/
           //Dictionary<string, string> dc1 = new Dictionary<string, string>();
           //dc1.Add("genre", "李赞红");
           //dc1.Add("ISBN", "2-3631-4");
           //Dictionary<strin插入g, string> dc2 = new Dictionary<string, string>();
           //dc2.Add("title", "CS从入门到精通");
           //dc2.Add("author", "候捷");
           //dc2.Add("price", "58.3");
           //xHelper.InsertNode(path, "bookstore", "book", dc1, dc2);
 
           /*修改*/
           //xHelper.UpdateNodeAttribute(path, "bookstore", "genre", "李赞红", "李");
           //xHelper.UpdateChildNodeAttribute(path, "bookstore", "title", "CS从入门到精通", "cs");
 
           /*删除节点*/
           //xHelper.DeleteNode(path, "bookstore", "genre", "李");
 
           //Response.Write(xHelper.GetNodeAttribute(path, "bookstore", "genre"));
           //Response.Write(xHelper.GetNodeChildAttribute(path, "bookstore", "price"));

4. Through xml data binding

xml to DataTable

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转xml*/
       public  string DataTableToXml(DataTable dt)
       {
           if (dt != null)
           {
               MemoryStream ms = null;
               XmlTextWriter XmlWt = null;
               try
               {
                   ms = new MemoryStream();
                   //根据ms实例化XmlWt
                   XmlWt = new XmlTextWriter(ms, Encoding.Unicode);
                   //获取ds中的数据
                   dt.WriteXml(XmlWt);
                   int count = (int)ms.Length;
                   byte[] temp = new byte[count];
                   ms.Seek(0, SeekOrigin.Begin);
                   ms.Read(temp, 0, count);
                   //返回Unicode编码的文本
                   UnicodeEncoding ucode = new UnicodeEncoding();
                   string returnValue = ucode.GetString(temp).Trim();
                   return returnValue;
               }
               catch (System.Exception ex)
               {
                   throw ex;
               }
               finally
               {
                   //释放资源
                   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<T> 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<Person> list = new List<Person> { new Person { Name = "Xuj", Age = 20 }, new Person { Name = "duj", Age = 20 }, new Person { Name = "fuj", Age = 20 } };
            string s = CXmlSerializer<List<Person>>.Serialize(list);

The above is the detailed content of A detailed introduction to the summary of how to use xml. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Parse and Utilize XML-Based RSS FeedsHow to Parse and Utilize XML-Based RSS FeedsApr 16, 2025 am 12:05 AM

RSSfeedsuseXMLtosyndicatecontent;parsingtheminvolvesloadingXML,navigatingitsstructure,andextractingdata.Applicationsincludebuildingnewsaggregatorsandtrackingpodcastepisodes.

RSS Documents: How They Deliver Your Favorite ContentRSS Documents: How They Deliver Your Favorite ContentApr 15, 2025 am 12:01 AM

RSS documents work by publishing content updates through XML files, and users subscribe and receive notifications through RSS readers. 1. Content publisher creates and updates RSS documents. 2. The RSS reader regularly accesses and parses XML files. 3. Users browse and read updated content. Example of usage: Subscribe to TechCrunch's RSS feed, just copy the link to the RSS reader.

Building Feeds with XML: A Hands-On Guide to RSSBuilding Feeds with XML: A Hands-On Guide to RSSApr 14, 2025 am 12:17 AM

The steps to build an RSSfeed using XML are as follows: 1. Create the root element and set the version; 2. Add the channel element and its basic information; 3. Add the entry element, including the title, link and description; 4. Convert the XML structure to a string and output it. With these steps, you can create a valid RSSfeed from scratch and enhance its functionality by adding additional elements such as release date and author information.

Creating RSS Documents: A Step-by-Step TutorialCreating RSS Documents: A Step-by-Step TutorialApr 13, 2025 am 12:10 AM

The steps to create an RSS document are as follows: 1. Write in XML format, with the root element, including the elements. 2. Add, etc. elements to describe channel information. 3. Add elements, each representing a content entry, including,,,,,,,,,,,. 4. Optionally add and elements to enrich the content. 5. Ensure the XML format is correct, use online tools to verify, optimize performance and keep content updated.

XML's Role in RSS: The Foundation of Syndicated ContentXML's Role in RSS: The Foundation of Syndicated ContentApr 12, 2025 am 12:17 AM

The core role of XML in RSS is to provide a standardized and flexible data format. 1. The structure and markup language characteristics of XML make it suitable for data exchange and storage. 2. RSS uses XML to create a standardized format to facilitate content sharing. 3. The application of XML in RSS includes elements that define feed content, such as title and release date. 4. Advantages include standardization and scalability, and challenges include document verbose and strict syntax requirements. 5. Best practices include validating XML validity, keeping it simple, using CDATA, and regularly updating.

From XML to Readable Content: Demystifying RSS FeedsFrom XML to Readable Content: Demystifying RSS FeedsApr 11, 2025 am 12:03 AM

RSSfeedsareXMLdocumentsusedforcontentaggregationanddistribution.Totransformthemintoreadablecontent:1)ParsetheXMLusinglibrarieslikefeedparserinPython.2)HandledifferentRSSversionsandpotentialparsingerrors.3)Transformthedataintouser-friendlyformatsliket

Is There an RSS Alternative Based on JSON?Is There an RSS Alternative Based on JSON?Apr 10, 2025 am 09:31 AM

JSONFeed is a JSON-based RSS alternative that has its advantages simplicity and ease of use. 1) JSONFeed uses JSON format, which is easy to generate and parse. 2) It supports dynamic generation and is suitable for modern web development. 3) Using JSONFeed can improve content management efficiency and user experience.

RSS Document Tools: Building, Validating, and Publishing FeedsRSS Document Tools: Building, Validating, and Publishing FeedsApr 09, 2025 am 12:10 AM

How to build, validate and publish RSSfeeds? 1. Build: Use Python scripts to generate RSSfeed, including title, link, description and release date. 2. Verification: Use FeedValidator.org or Python script to check whether RSSfeed complies with RSS2.0 standards. 3. Publish: Upload RSS files to the server, or use Flask to generate and publish RSSfeed dynamically. Through these steps, you can effectively manage and share content.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.