SoFunction
Updated on 2025-03-08

Summary of common methods for operating XML in C#

In the development of .net, XML files are often operated. Since XML files can be transmitted across platforms, more applications are used in data transmission. The following commonly used XML operation methods are summarized:

1. Create an XML document:

  /// <summary>
  /// Create XML document  /// </summary>
  /// <param name="name">root node name</param>  /// <param name="type">A property value of the root node</param>  /// <returns>XmlDocument object</returns>  public static XmlDocument CreateXmlDocument(string name, string type)
  {
   XmlDocument doc;
   try
   {
    doc = new XmlDocument();
    ("&lt;" + name + "/&gt;");
    var rootEle = ;
    rootEle?.SetAttribute("type", type);
   }
   catch (Exception er)
   {
    throw new Exception(());
   }
   return doc;
  }

2. Read data in XML documents:

  /// &lt;summary&gt;
  /// Read data  /// &lt;/summary&gt;
  /// <param name="path">path</param>  /// <param name="node">node</param>  /// <param name="attribute">Attribute name, return the attribute value when it is not empty, otherwise return the concatenated value</param>  /// &lt;returns&gt;string&lt;/returns&gt;
  public static string Read(string path, string node, string attribute)
  {
   var value = "";
   try
   {
    var doc = new XmlDocument();
    (path);
    var xn = (node);
    if (xn != null &amp;&amp;  != null)
     value = (("") ?  : [attribute].Value);
   }
   catch (Exception er)
   {
    throw new Exception(());
   }
   return value;
  }

3. Insert data into XML documents:

  /// &lt;summary&gt;
  /// Insert data  /// &lt;/summary&gt;
  /// <param name="path">path</param>  /// <param name="node">node</param>  /// <param name="element">Element name, insert a new element when it is not empty, otherwise insert an attribute in this 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">value</param>  /// &lt;returns&gt;&lt;/returns&gt;
  public static void Insert(string path, string node, string element, string attribute, string value)
  {
   try
   {
    var doc = new XmlDocument();
    (path);
    var xn = (node);
    if ((""))
    {
     if (!(""))
     {
      var xe = (XmlElement)xn;
      xe?.SetAttribute(attribute, value);
      //xe?.SetAttribute(attribute, value);
     }
    }
    else
    {
     var xe = (element);
     if ((""))
       = value;
     else
      (attribute, value);
     xn?.AppendChild(xe);
    }
    (path);
   }
   catch (Exception er)
   {
    throw new Exception(());
   }
  }

4. Modify the data in the XML document:

  /// &lt;summary&gt;
  /// Modify data  /// &lt;/summary&gt;
  /// <param name="path">path</param>  /// <param name="node">node</param>  /// <param name="attribute">Attribute name, modify the attribute value of the node when it is not empty, otherwise modify the node value</param>  /// <param name="value">value</param>  /// &lt;returns&gt;&lt;/returns&gt;
  public static void Update(string path, string node, string attribute, string value)
  {
   try
   {
    var doc = new XmlDocument();
    (path);
    var xn = (node);
    var xe = (XmlElement)xn;
    if ((""))
    {
     if (xe != null)  = value;
    }
    else
    {
     xe?.SetAttribute(attribute, value);
    }
    (path);
   }
   catch (Exception er)
   {
    throw new Exception(());
   }
  }

5. Delete data in XML documents:

  /// &lt;summary&gt;
  /// Delete data  /// &lt;/summary&gt;
  /// <param name="path">path</param>  /// <param name="node">node</param>  /// <param name="attribute">Attribute name, delete the node attribute value when it is not empty, otherwise delete the node value</param>  /// &lt;returns&gt;&lt;/returns&gt;
  public static void Delete(string path, string node, string attribute)
  {
   try
   {
    var doc = new XmlDocument();
    (path);
    var xn = (node);
    var xe = (XmlElement)xn;
    if ((""))
    {
     xn?.ParentNode?.RemoveChild(xn);
    }
    else
    {
     xe?.RemoveAttribute(attribute);
    }
    (path);
   }
   catch (Exception er)
   {
    throw new Exception(());
   }
  }

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

  /// &lt;summary&gt;
  /// Obtain the node data of the specified node in the xml file  /// &lt;/summary&gt;
  /// &lt;param name="path"&gt;&lt;/param&gt;
  /// &lt;param name="nodeName"&gt;&lt;/param&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  public static string GetNodeInfoByNodeName(string path, string nodeName)
  {
   var xmlString = ;
   try
   {
    var xml = new XmlDocument();
    (path);
    var root = ;
    if (root == null) return xmlString;
    var node = ("//" + nodeName);
    if (node != null)
    {
     xmlString = ;
    }
   }
   catch (Exception er)
   {
    throw new Exception(());
   }
   return xmlString;
  }

7. Get the attributes of the XML specified node:

  /// &lt;summary&gt; 
  /// Function: Read the specified attribute value of the specified node  /// &lt;/summary&gt;
  /// &lt;param name="path"&gt;&lt;/param&gt;
  /// <param name="strNode">Node Name</param>  /// <param name="strAttribute">Properties of this node</param>  /// &lt;returns&gt;&lt;/returns&gt; 
  public string GetXmlNodeAttributeValue(string path, string strNode, string strAttribute)
  {
   var strReturn = "";
   try
   {
    var xml = new XmlDocument();
    (path);
    //Get nodes based on the specified path    var xmlNode = (strNode);
    if (xmlNode != null)
    {
     //Get the node's attributes and loop out the required attribute values     var xmlAttr = ;
     if (xmlAttr == null) return strReturn;
     for (var i = 0; i &lt; ; i++)
     {
      if ((i).Name != strAttribute) continue;
      strReturn = (i).Value;
      break;
     }
    }
   }
   catch (XmlException xmle)
   {
    throw new Exception();
   }
   return strReturn;
  }

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

 /// &lt;summary&gt; 
  /// Function: Set the attribute value of the node  /// &lt;/summary&gt;
  /// &lt;param name="path"&gt;&lt;/param&gt;
  /// <param name="xmlNodePath">Nodename</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();
    (path);
    //The properties of nodes that meet the conditions can be paid in batches    var xmlNode = (xmlNodePath);
    if (xmlNode == null) return;
    foreach (var xmlAttr in from XmlNode xn in xmlNode select )
    {
     if (xmlAttr == null) return;
     for (var i = 0; i &lt; ; i++)
     {
      if ((i).Name != xmlNodeAttribute) continue;
      (i).Value = xmlNodeAttributeValue;
      break;
     }
    }

   }
   catch (XmlException xmle)
   {
    throw new Exception();
   }
  }

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

  /// &lt;summary&gt;
  /// Read the specified node content in the XML resource  /// &lt;/summary&gt;
  /// <param name="source">XML resources</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 == )
   {
    (source);
   }
   else
   {
    (source);
   }
   var xe = ;
   XmlNode xn = null;
   if (xe != null)
   {
     xn= ("//" + nodeName);
    
   }
   return ;
  }

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

  /// &lt;summary&gt;
  /// Update the specified node content in the XML file  /// &lt;/summary&gt;
  /// <param name="filePath">File Path</param>  /// <param name="nodeName">Node name</param>  /// <param name="nodeValue">Update content</param>  /// <returns>Is the update successful</returns>  public static bool UpdateNode(string filePath, string nodeName, string nodeValue)
  {   
   try
   {
    bool flag;
    var xd = new XmlDocument();
    (filePath);
    var xe = ;
    if (xe == null) return false;
    var xn = ("//" + nodeName);
    if (xn != null)
    {
      = nodeValue;
     flag = true;
    }
    else
    {
     flag = false;
    }
    return flag;
   }
   catch (Exception ex)
   {
    throw new Exception();
   }
   
  }
Copy the code
11.Convert objects toXMLdocument,and save it to the specified directory:

Copy the code
  /// &lt;summary&gt;
  /// Convert the object to xml and write it to the xml file with the specified path  /// &lt;/summary&gt;
  /// <typeparam name="T">C#Object Name</typeparam> /// <param name="item">Object Instance</param>  /// <param name="path">path</param>  /// <param name="jjdbh">Large</param>  /// <param name="ends">End symbol (the path of the entire xml is similar to the following: C:\xmltest\, where path=C:\xmltest,jjdbh=201111,ends=send)</param>  /// &lt;returns&gt;&lt;/returns&gt;
  public static string WriteXml&lt;T&gt;(T item, string path, string jjdbh, string ends)
  {
   if ((ends))
   {
    //Default is send    ends = "send";
   }
   //Control the number of times the file is written   var i = 0;
   //Get the type of the current object, you can also use reflection typeof (object name)   var serializer = new XmlSerializer(());
   // xml path combination   object[] obj = { path, "\\", jjdbh, ends, ".xml" };
   var xmlPath = (obj);
   while (true)
   {
    try
    {
     //Creating a file using filestream will not cause "File is being occupied, use"     var fs = (xmlPath);
     ();
     TextWriter writer = new StreamWriter(xmlPath, false, Encoding.UTF8);
     var xml = new XmlSerializerNamespaces();
     (, );
     (writer, item, xml);
     ();
     ();
     break;
    }
    catch (Exception)
    {
     if (i &lt; 5)
     {
      i++;
      continue;
     }
     break;
    }
   }
   return SerializeToXmlStr&lt;T&gt;(item, true);
  }

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

  /// &lt;summary&gt; 
  /// Insert a child into an existing parent node  /// &lt;/summary&gt;
  /// &lt;param name="path"&gt;&lt;/param&gt;
  /// <param name="parentNodePath">parent node</param>  /// <param name="childnodename">childnodename</param>  public void AddChildNode(string path, string parentNodePath, string childnodename)
  {
   try
   {
    var xml = new XmlDocument();
    (path);
    var parentXmlNode = (parentNodePath);
    XmlNode childXmlNode = (childnodename);
    if ((parentXmlNode) != null)
    {
     //If this node exists     (childXmlNode);
    }
    else
    {
     //If it does not exist, add the parent node     GetXmlRoot(path).AppendChild(childXmlNode);
    }

   }
   catch (XmlException xmle)
   {
    throw new Exception();
   }
  }


The above method summarizes the .net4.5 version and c#6.0 syntax. I hope it will be helpful to everyone's learning and I hope everyone can support me more.