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

CSharp examples for System.Xml:XML Document

Description

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

Demo Code

// All rights reserved.
using System.Diagnostics;
using System.Collections.Specialized;
using System.Xml;
using System.Data;
using System;/* ww w  .  ja  v a2 s.com*/

public class Main{
        /// <summary>
        /// Deletes a field from all records on the specified path.
        /// </summary>
        /// <param name="path">The xml path.</param>
        /// <param name="field">The field to delete.</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>
        /// <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