Returns an array of values for the specified field for all rows on the path from XmlDocument. - CSharp System.Xml

CSharp examples for System.Xml:XML Document

Description

Returns an array of values for the specified field for all rows on the path from XmlDocument.

Demo Code

// All rights reserved.
using System.Diagnostics;
using System.Collections.Specialized;
using System.Xml;
using System.Data;
using System;// w  ww  .  ja  v  a  2  s. c om

public class Main{
        /// <summary>
        /// Returns an array of values for the specified field for all rows on
        /// the path.
        /// </summary>
        /// <param name="xpath">The xml path.</param>
        /// <param name="field">The desired field.</param>
        /// <returns>The array of string values for each row qualified by the path.
        /// A null is returned if the query results in 0 rows.</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 string[] QueryField(XmlDocument doc, string xpath, string field)
        {
            VerifyParameters(doc, xpath);

            if (field == null)
            {
                throw (new ArgumentNullException("field cannot be null."));
            }

            XmlNodeList nodeList = doc.LastChild.SelectNodes(xpath);
            string[] s = null;
            if (nodeList.Count != 0)
            {
                s = new string[nodeList.Count];
                int i = 0;
                foreach (XmlNode node in nodeList)
                {
                    s[i++] = node.Attributes[field].Value;
                }
            }
            return s;
        }
}

Related Tutorials