Update a single field in all records in the specified path in XmlDocument. - CSharp System.Xml

CSharp examples for System.Xml:XML Document

Description

Update a single field in all records in the specified path in XmlDocument.

Demo Code

// All rights reserved.
using System.Diagnostics;
using System.Collections.Specialized;
using System.Xml;
using System.Data;
using System;/* w  ww .j a v  a2s  . c  o m*/

public class Main{
        #endregion

        #region Update
        /// <summary>
        /// Update a single field in all records in the specified path.
        /// </summary>
        /// <param name="doc">The XmlDocument whose node will be udpated.</param>
        /// <param name="xpath">The xml path.</param>
        /// <param name="field">The field name to update.</param>
        /// <param name="val">The new value.</param>
        /// <returns>The number of records affected.</returns>
        /// <exception cref="System.ArgumentNullException">Thrown when an argument is null.</exception>
        /// <remarks>
        /// The "doc" variable must have a root node.  The path should not contain the root node.
        /// The path can contain only the node names or it can contain attributes in XPath query form.
        /// For example to update an "Address" node at the bottom, the following is a valid xpath query
        ///     xpath = "University[@Name='UT']/Student[@Id=12222]/Address"
        /// </remarks>
        public static int Update(XmlDocument doc, string xpath, string field, string val)
        {
            VerifyParameters(doc, xpath);
            if (field == null)
            {
                throw (new ArgumentNullException("field cannot be null."));
            }
            if (val == null)
            {
                throw (new ArgumentNullException("val cannot be null."));
            }

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            XmlNodeList nodeList = doc.LastChild.SelectNodes(xpath);
            foreach (XmlNode node in nodeList)
            {
                if (!SetAttributeValue(node, field, val))
                    sb.Append(field + " is not an attribute of: " + NodeToString(node) + "\n");
            }
            if (sb.Length > 0) throw new Exception("Failed to add nodes because:\n" + sb.ToString());
            return nodeList.Count;
        }
}

Related Tutorials