Deletes a field from all XML records on the specified path. - CSharp System.Xml

CSharp examples for System.Xml:XPath

Description

Deletes a field from all XML records on the specified path.

Demo Code


using System.Diagnostics;
using System.Collections.Specialized;
using System.Xml;
using System.Data;
using System;//w w  w  . j av  a 2  s  .  c o  m

public class Main{
        /// <summary>
      /// Deletes a field from all records on the specified path.
      /// </summary>
      /// <param name="xpath">The xml path.</param>
      /// <param name="field">The field to delete.</param>
      /// <param name="doc"></param>
      /// <returns>The number of records affected.</returns>
      /// <exception cref="System.ArgumentNullException">Thrown when an argument is null.</exception>
      /// <remarks>Additional exceptions may be thrown by the XmlDocument class.</remarks>
      public static int Delete(XmlDocument doc, string xpath, string field)
      {
         VerifyParameters(doc, xpath);
         if (field==null)
         {
            throw(new ArgumentNullException("field cannot be null."));
         }

         XmlNodeList nodeList=doc.SelectNodes(xpath);
         foreach(XmlNode node in nodeList)
         {
            XmlAttribute attrib=node.Attributes[field];
            node.Attributes.Remove(attrib);
         }
         return nodeList.Count;
      }
        #endregion

      #region Delete
      /// <summary>
      /// Deletes all records of the specified path.
      /// </summary>
      /// <param name="xpath">The xml XPath query to get to the bottom node.</param>
      /// <param name="doc"></param>
      /// <returns>The number of records deleted.</returns>
      /// <exception cref="System.ArgumentNullException">Thrown when an argument is null.</exception>
      /// <remarks>Additional exceptions may be thrown by the XmlDocument class.</remarks>
      public static int Delete(XmlDocument doc, string xpath)
      {
         VerifyParameters(doc, xpath);

         XmlNodeList nodeList = doc.LastChild.SelectNodes(xpath);
         foreach(XmlNode node in nodeList)
         {
            node.ParentNode.RemoveChild(node);
         }
         return nodeList.Count;
      }
}

Related Tutorials