Inserts a record with multiple values at bottom of hierarchy into XmlDocument. - CSharp System.Xml

CSharp examples for System.Xml:XML Document

Description

Inserts a record with multiple values at bottom of hierarchy into XmlDocument.

Demo Code

// All rights reserved.
using System.Diagnostics;
using System.Collections.Specialized;
using System.Xml;
using System.Data;
using System;/*from   w  w w.j a va2  s.  c  o m*/

public class Main{
        /// <summary>
        /// Inserts a record with multiple values at bottom of hierarchy. This is analogous to inserting 
        /// a column of data.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="xpath">The xml XPath query to get to the bottom node.</param>
        /// <param name="field">Name of the attribute to be created at node inserted.</param>
        /// <param name="values">Values that will be inserted that correspond to the field name.</param>
        /// <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 insert an "Address" node at the bottom, the following is a valid xpath query
        ///     xpath = "University[@Name='UT']/Student[@Id=12222]/Address"
        /// </remarks>
        public static void Insert(XmlDocument doc, string xpath, string field, string[] values)
        {
            VerifyParameters(doc, xpath);

            XmlNode node;
            foreach (string val in values)
            {
                node = Insert(doc, xpath);
                CreateAttribute(node, field, val);
            }
        }
        /// <summary>
        /// Inserts a record with multiple fields from a DataTable at bottom of the hierarchy.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="xpath">The xml XPath query to get to the bottom node.</param>
        /// <param name="rowValues">The DataRow values that will be added as attributes.</param>
        public static void Insert(XmlDocument doc, string xpath, DataTable table)
        {
            VerifyParameters(doc, xpath);
            if (table == null)
            {
                throw (new ArgumentNullException("table cannot be null."));
            }

            foreach (DataRow row in table.Rows)
            {
                Insert(doc, xpath, row);
            }
        }
        /// <summary>
        /// Inserts a record with multiple fields at bottom of the hierarchy.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="xpath">The xml XPath query to get to the bottom node.</param>
        /// <param name="rowValues">The DataRow values that will be added as attributes.</param>
        /// <remarks>
        /// The columns names of the DataRow will become the attribute names and 
        /// the row values of the DataRow will be the attribute values.
        /// 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 insert an "Address" node at the bottom, the following is a valid xpath query
        ///     xpath = "University[@Name='UT']/Student[@Id=12222]/Address"
        /// </remarks>
        public static void Insert(XmlDocument doc, string xpath, DataRow rowValues)
        {
            VerifyParameters(doc, xpath);
            if (rowValues == null)
            {
                throw (new ArgumentNullException("rowValues cannot be null."));
            }

            XmlNode node = Insert(doc, xpath);
            foreach (DataColumn col in rowValues.Table.Columns)
            {
                CreateAttribute(node, col.ColumnName, rowValues[col.ColumnName].ToString());
            }
        }
        /// <summary>
        /// Insert a record with multiple fields at the bottom of the hierarchy.
        /// </summary>
        /// <param name="xpath">The xml XPath query to get to the bottom node.</param>
        /// <param name="fields">The array of fields as field/value pairs.</param>
        /// <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 insert an "Address" node at the bottom, the following is a valid xpath query
        ///     xpath = "University[@Name='UT']/Student[@Id=12222]/Address"
        /// </remarks>
        public static void Insert(XmlDocument doc, string xpath, NameValueCollection nameValuePairs)
        {
            VerifyParameters(doc, xpath);
            if (nameValuePairs == null)
            {
                throw (new ArgumentNullException("fields cannot be null."));
            }

            XmlNode node = Insert(doc, xpath);

            System.Collections.IEnumerator iterator = nameValuePairs.GetEnumerator();
            string field, val;
            while (iterator.MoveNext())
            {
                field = iterator.Current.ToString();
                val = nameValuePairs[field];
                CreateAttribute(node, field, val);
            }
        }
        /// <summary>
        /// Inserts a record with a single field at the bottom of the hierarchy.
        /// </summary>
        /// <param name="xpath">The xml XPath query to get to the bottom node.</param>
        /// <param name="field">The field to add to the record.</param>
        /// <param name="val">The value assigned to the field.</param>
        /// <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 insert an "Address" node at the bottom, the following is a valid xpath query
        ///     xpath = "University[@Name='UT']/Student[@Id=12222]/Address"
        /// </remarks>
        public static void Insert(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."));
            }

            XmlNode node = Insert(doc, xpath);
            CreateAttribute(node, field, val);
        }
        /// <summary>
        /// Inserts an record with a multiple fields at the bottom of the hierarchy.
        /// </summary>
        /// <param name="doc">The XmlDocument to which the node will be inserted.</param>
        /// <param name="xpath">The xml XPath query to get to the bottom node.</param>
        /// <param name="fields">The attribute names that will be created for the node inserted.</param>
        /// <param name="values">The corresponding value of each field.</param>
        /// <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 insert an "Address" node at the bottom, the following is a valid xpath query
        ///     xpath = "University[@Name='UT']/Student[@Id=12222]/Address"
        /// </remarks>
        public static void Insert(XmlDocument doc, string xpath, string[] fields, string[] values)
        {
            VerifyParameters(doc, xpath);
            if (fields == null)
            {
                throw (new ArgumentNullException("field cannot be null."));
            }
            if (values == null)
            {
                throw (new ArgumentNullException("val cannot be null."));
            }

            XmlNode node = Insert(doc, xpath);

            for (int i = 0; i < fields.Length; i++)
            {
                CreateAttribute(node, fields[i], values[i]);
            }
        }
        #endregion

        #region ? Copyright 2005, Marc Clifton, All Rights Reserved - XmlDatase methods
        /*
      (c) 2005, Marc Clifton
      All Rights Reserved
 
      Redistribution and use in source and binary forms, with or without modification,
      are permitted provided that the following conditions are met:

      Redistributions of source code must retain the above copyright notice, this list
      of conditions and the following disclaimer. 

      Redistributions in binary form must reproduce the above copyright notice, this
      list of conditions and the following disclaimer in the documentation and/or other
      materials provided with the distribution. 

      Neither the name of the Marc Clifton nor the names of its contributors may be
      used to endorse or promote products derived from this software without specific
      prior written permission. 

      THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
      ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
      WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
      IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
      INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
      BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
      DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
      LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
      OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
      ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      */

        #region Disclosure
        /*
       * With Marc Clifton's permission, the methods in this section were copied and 
       * modified to be used in XmlHelper.  The original source code is located at:
       * http://www.codeproject.com/dotnet/XmlDb.asp
      */
        #endregion


        #region Insert
        /// <summary>
        /// Inserts an empty record at the bottom of the hierarchy, creating the
        /// tree as required.
        /// </summary>
        /// <param name="doc">The XmlDocument to which the node will be inserted.</param>
        /// <param name="xpath">The xml XPath query to get to the bottom node.</param>
        /// <returns>The XmlNode inserted into the hierarchy.</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 insert an "Address" node at the bottom, the following is a valid xpath query
        ///     xpath = "University[@Name='UT']/Student[@Id=12222]/Address"
        /// </remarks>
        public static XmlNode Insert(XmlDocument doc, string xpath)
        {
            VerifyParameters(doc, xpath);

            string path2 = xpath.Trim('/');   // get rid of slashes in front and back
            string[] segments = path2.Split('/');

            XmlNode firstNode = doc.LastChild;
            int nodeIndex = 0;

            if (segments.Length > 1)
            {
                ///
                /// Check if we can access the last node.  This comes in handy in cases when the path
                /// contains attributes.  For example: "University[@Name='UT']/Student[@Id=12222]/Address"
                /// In example above we would want to get access to last node directly
                ///
                int pos = path2.LastIndexOf('/');
                string path3 = path2.Substring(0, pos);
                XmlNode parentNode = doc.LastChild.SelectSingleNode(path3);
                if (parentNode != null)
                {
                    firstNode = parentNode;
                    nodeIndex = segments.Length - 1;
                }
            }

            XmlNode lastNode = InsertNode(firstNode, segments, nodeIndex);
            return lastNode;
        }
}

Related Tutorials