Summary of Common Methods for Manipulating XML in C#

Reprinted from: http://www.cnblogs.com/pengze0902/p/5947997.html 

In the project development of .net, XML files are often operated. Since XML files can realize cross-platform transmission, more applications are in data transmission. Here are some commonly used XML operation methods:

1. Create an XML document:

copy code
        /// <summary>
        /// Create an XML document
        /// </summary>
        /// <param name="name">root node name</param>
        /// <param name="type">An attribute value of the root node</param>
        /// <returns>XmlDocument object</returns>     
        public static XmlDocument CreateXmlDocument(string name, string type)
        {
            XmlDocument doc;
            try
            {
                doc = new XmlDocument();
                doc.LoadXml("<" + name + "/>");
                var rootEle = doc.DocumentElement;
                rootEle?.SetAttribute("type", type);
            }
            catch (Exception er)
            {
                throw new Exception(er.ToString());
            }
            return doc;
        }
copy code

2. Read the data in the XML document:

copy code
        /// <summary>
        /// read data
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="attribute">Attribute name, return the attribute value if it is not empty, otherwise return the concatenated value</param>
        /// <returns>string</returns>
        public static string Read(string path, string node, string attribute)
        {
            var value = "";
            try
            {
                var doc = new XmlDocument();
                doc.Load(path);
                var xn = doc.SelectSingleNode(node);
                if (xn != null && xn.Attributes != null)
                    value = (attribute.Equals("") ? xn.InnerText : xn.Attributes[attribute].Value);
            }
            catch (Exception er)
            {
                throw new Exception(er.ToString());
            }
            return value;
        }
copy code

3. Insert data into the XML document:

copy code
        /// <summary>
        /// Insert data
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="element">Element name, insert a new element when it is not empty, otherwise insert the attribute in the element</param>
        /// <param name="attribute">Attribute name, insert the attribute value of the element when it is not empty, otherwise insert the element value</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        public static void Insert(string path, string node, string element, string attribute, string value)
        {
            try
            {
                var doc = new XmlDocument();
                doc.Load(path);
                var xn = doc.SelectSingleNode(node);
                if (element.Equals(""))
                {
                    if (!attribute.Equals(""))
                    {
                        var xe = (XmlElement)xn;
                        xe?.SetAttribute(attribute, value);
                        //xe?.SetAttribute(attribute, value);
                    }
                }
                else
                {
                    var xe = doc.CreateElement(element);
                    if (attribute.Equals(""))
                        xe.InnerText = value;
                    else
                        xe.SetAttribute(attribute, value);
                    xn?.AppendChild(xe);
                }
                doc.Save(path);
            }
            catch (Exception er)
            {
                throw new Exception(er.ToString());
            }
        }
copy code

4. Modify the data in the XML document:

copy code
        /// <summary>
        /// change the data
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="attribute">Attribute name, modify the node attribute value when it is not empty, otherwise modify the node value</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        public static void Update(string path, string node, string attribute, string value)
        {
            try
            {
                var doc = new XmlDocument();
                doc.Load(path);
                var xn = doc.SelectSingleNode(node);
                var xe = (XmlElement)xn;
                if (attribute.Equals(""))
                {
                    if (xe != null) xe.InnerText = value;
                }
                else
                {
                    xe?.SetAttribute(attribute, value);
                }
                doc.Save(path);
            }
            catch (Exception er)
            {
                throw new Exception(er.ToString());
            }
        }
copy code

5. Delete the data in the XML document:

copy code
        /// <summary>
        /// delete data
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="attribute">Attribute name, delete the node attribute value if it is not empty, otherwise delete the node value</param>
        /// <returns></returns>
        public static void Delete(string path, string node, string attribute)
        {
            try
            {
                var doc = new XmlDocument();
                doc.Load(path);
                var xn = doc.SelectSingleNode(node);
                var xe = (XmlElement)xn;
                if (attribute.Equals(""))
                {
                    xn?.ParentNode?.RemoveChild(xn);
                }
                else
                {
                    xe?.RemoveAttribute(attribute);
                }
                doc.Save(path);
            }
            catch (Exception er)
            {
                throw new Exception(er.ToString());
            }
        }
copy code

6. Read the specified node data in the XML document:

copy code
        /// <summary>
        /// Get the node data of the specified node in the xml file
        /// </summary>
        /// <param name="path"></param>
        /// <param name="nodeName"></param>
        /// <returns></returns>
        public static string GetNodeInfoByNodeName(string path, string nodeName)
        {
            var xmlString = string.Empty;
            try
            {
                var xml = new XmlDocument();
                xml.Load(path);
                var root = xml.DocumentElement;
                if (root == null) return xmlString;
                var node = root.SelectSingleNode("//" + nodeName);
                if (node != null)
                {
                    xmlString = node.InnerText;
                }
            }
            catch (Exception er)
            {
                throw new Exception(er.ToString());
            }
            return xmlString;
        }
copy code

7. Get the attributes of the XML specified node:

copy code
        /// <summary>  
        /// Function: Read the specified attribute value of the specified node     
        /// </summary>
        /// <param name="path"></param>
        /// <param name="strNode">Node name</param>  
        /// <param name="strAttribute">Attribute of this node</param>  
        /// <returns></returns>  
        public string GetXmlNodeAttributeValue(string path, string strNode, string strAttribute)
        {
            var strReturn = "";
            try
            {
                var xml = new XmlDocument();
                xml.Load(path);
                //Get the node according to the specified path  
                var xmlNode = xml.SelectSingleNode(strNode);
                if (xmlNode != null)
                {
                    / / Get the attributes of the node, and loop out the required attribute values  
                    var xmlAttr = xmlNode.Attributes;
                    if (xmlAttr == null) return strReturn;
                    for (var i = 0; i < xmlAttr.Count; i++)
                    {
                        if (xmlAttr.Item(i).Name != strAttribute) continue;
                        strReturn = xmlAttr.Item(i).Value;
                        break;
                    }
                }
            }
            catch (XmlException xmle)
            {
                throw new Exception(xmle.Message);
            }
            return strReturn;
        }
copy code

8. Set the attributes of the specified node in the XML document:

copy code
/// <summary>  
        /// Function: Set the attribute value of the node     
        /// </summary>
        /// <param name="path"></param>
        /// <param name="xmlNodePath">Node name</param>  
        /// <param name="xmlNodeAttribute">Attribute name</param>  
        /// <param name="xmlNodeAttributeValue">Attribute value</param>  
        public void SetXmlNodeAttributeValue(string path, string xmlNodePath, string xmlNodeAttribute, string xmlNodeAttributeValue)
        {
            try
            {
                var xml = new XmlDocument();
                xml.Load(path);
                //You can pay values ​​for the attributes of eligible nodes in batches  
                var xmlNode = xml.SelectNodes(xmlNodePath);
                if (xmlNode == null) return;
                foreach (var xmlAttr in from XmlNode xn in xmlNode select xn.Attributes)
                {
                    if (xmlAttr == null) return;
                    for (var i = 0; i < xmlAttr.Count; i++)
                    {
                        if (xmlAttr.Item(i).Name != xmlNodeAttribute) continue;
                        xmlAttr.Item(i).Value = xmlNodeAttributeValue;
                        break;
                    }
                }

            }
            catch (XmlException xmle)
            {
                throw new Exception(xmle.Message);
            }
        }
copy code

9. Read the value of the specified node in the XML document:

copy code
        /// <summary>
        /// Read the specified node content in the XML resource
        /// </summary>
        /// <param name="source">XML resource</param>
        /// <param name="xmlType">XML resource type: file, string</param>
        /// <param name="nodeName">node name</param>
        /// <returns>Node content</returns>
        public static object GetNodeValue(string source, XmlType xmlType, string nodeName)
        {
            var xd = new XmlDocument();
            if (xmlType == XmlType.File)
            {
                xd.Load(source);
            }
            else
            {
                xd.LoadXml (source);
            }
            var xe = xd.DocumentElement;
            XmlNode xn = null;
            if (xe != null)
            {
                 xn= xe.SelectSingleNode("//" + nodeName);
                
            }
            return xn.InnerText;
        }
copy code

10. Update the content of the specified node in the XML document:

copy code
        /// <summary>
        /// Update the content of the specified node in the XML file
        /// </summary>
        /// <param name="filePath">file path</param>
        /// <param name="nodeName">node name</param>
        /// <param name="nodeValue">Update Content</param>
        /// <returns>Whether the update was successful</returns>
        public static bool UpdateNode(string filePath, string nodeName, string nodeValue)
        {            
            try
            {
                bool flag;
                var xd = new XmlDocument();
                xd.Load(filePath);
                var xe = xd.DocumentElement;
                if (xe == null) return false;
                var xn = xe.SelectSingleNode("//" + nodeName);
                if (xn != null)
                {
                    xn.InnerText = nodeValue;
                    flag = true;
                }
                else
                {
                    flag = false;
                }
                return flag;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
           
        }
copy code

11. Convert the object into an XML file and store it in the specified directory:

copy code
        /// <summary>
        /// Convert the object to xml and write it to the xml file of the specified path
        /// </summary>
        /// <typeparam name="T">C# object name</typeparam>
        /// <param name="item">Object instance</param>
        /// <param name="path">路径</param>
        /// <param name="jjdbh">标号</param>
        /// <param name="ends">End symbol (the path of the entire xml is similar to the following: C:\xmltest\201111send.xml, where path=C:\xmltest,jjdbh=201111,ends=send)</param>
        /// <returns></returns>
        public static string WriteXml<T>(T item, string path, string jjdbh, string ends)
        {
            if (string.IsNullOrEmpty(ends))
            {
                // default to send
                ends = "send";
            }
            //Control the number of times to write to the file
            var i = 0;
            //Get the type of the current object, you can also use reflection typeof(object name)
            var serializer = new XmlSerializer(item.GetType());
            //path combination of xml
            object[] obj = { path, "\\", jjdbh, ends, ".xml" };
            var xmlPath = string.Concat(obj);
            while (true)
            {
                try
                {
                    //Create a file with filestream method will not appear "the file is occupied, use File.create" will not work
                    var fs = System.IO.File.Create(xmlPath);
                    fs.Close();
                    TextWriter writer = new StreamWriter(xmlPath, false, Encoding.UTF8);
                    var xml = new XmlSerializerNamespaces();
                    xml.Add(string.Empty, string.Empty);
                    serializer.Serialize(writer, item, xml);
                    writer.Flush();
                    writer.Close();
                    break;
                }
                catch (Exception)
                {
                    if (i < 5)
                    {
                        i++;
                        continue;
                    }
                    break;
                }
            }
            return SerializeToXmlStr<T>(item, true);
        }
copy code

12. Insert a child node into an existing parent node:

copy code
        /// <summary>  
        /// Insert a child node into an existing parent node  
        /// </summary>
        /// <param name="path"></param>
        /// <param name="parentNodePath">parent node</param>
        /// <param name="childnodename">child node name</param>  
        public void AddChildNode(string path, string parentNodePath, string childnodename)
        {
            try
            {
                var xml = new XmlDocument();
                xml.Load(path);
                var parentXmlNode = xml.SelectSingleNode(parentNodePath);
                XmlNode childXmlNode = xml.CreateElement(childnodename);
                if ((parentXmlNode) != null)
                {
                    //if this node exists    
                    parentXmlNode.AppendChild(childXmlNode);
                }
                else
                {
                    //If it doesn't exist, put the parent node and add it  
                    GetXmlRoot(path).AppendChild(childXmlNode);
                }

            }
            catch (XmlException xmle)
            {
                throw new Exception(xmle.Message);
            }
        }
copy code

   The above methods are summarized using .net4.5 version and c#6.0 syntax

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324852400&siteId=291194637