Parse the XML file to print all the child nodes attribute value

You can use this code to parse the XML file. This program gets the parentnode as an input and prints its all child nodes values.

Output:
--------
Suppose XML file looks like below:
<mostouterparent>
    <parentnode myattribute="att1">
          //Other nodes//
    </userGroup>
    <parentnode myattribute="att2" >
            //Other nodes//
    </userGroup>
    <parentnode myattribute="att3" >
           //Other nodes//
    </userGroup>
    <parentnode myattribute="att3" >
           //Other nodes//
    </userGroup>
  </mostouterparent>

You have given input as parentnode then output will be:
att1
att2
att3
att4

If you want the values of parentnodes childs //other nodes// then you will need to iterate for loop given below one level inside like below:

foreach (XmlNode unode in childNodes) {                  
      foreach (XmlNode innerChilds in unode)  {
               //Retrieve the values here
      }
}

Complete C# Program
-----------------------
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Xml;
using System.Data;
using System.Text;
using System.Xml.Schema;
using System.Diagnostics;
using System.Globalization;
using System.DirectoryServices;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Runtime.Remoting.Lifetime;


namespace ParseTheXMLFileForUser
{
    class Program
    {       
        private static XmlDocument m_xml_doc = new XmlDocument();
        private static XmlNamespaceManager m_namespace_mgr;
        static void Main(string[] args)
        {   
            printAllChilds("Node name in XML");
        }
        //This function will display all the commands that user can execute//
        static private void printAllChilds(string parentnode)
        {
            try {
                LoadFromDataSource(@"C:\my.xml",new Uri(@"C:\my.xsd"));
                XmlNodeList childNodes = m_xml_doc.GetElementsByTagName(parentnode);
                ArrayList userGroupAliases = new ArrayList();
                foreach (XmlNode unode in childNodes) {                   
                        try {
                            userGroupAliases.Add(unode.Attributes["Child Attribute"].Value.ToLower());
                        } catch {
                            //ignore
                        }
                }
                foreach (string tmp in userGroupAliases)
                    Console.WriteLine(tmp);
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }
        }
        private static void LoadFromDataSource(string connectionString, Uri schemaFileUri)
        {
            XmlReader xr = null;
            try
            {
                // create a xmlreadersettings object
                // to specify how to read in the file
                XmlReaderSettings xrs = new XmlReaderSettings();
                xrs.CloseInput = true;
                xrs.IgnoreComments = true;

                xrs.Schemas.Add(null, schemaFileUri.AbsoluteUri);
                xrs.ValidationType = ValidationType.Schema;

                // read in the file
                xr = XmlReader.Create(connectionString, xrs);

                // load the xml reader into the xml document.
                m_xml_doc.Load(xr);

                // close the xmlreader
                xr.Close();

                // create the namespace manager using the xml file name table
                m_namespace_mgr = new XmlNamespaceManager(m_xml_doc.NameTable);

                // if there is a default namespace specified in the
                // xml file then it needs to be added to the namespace
                // manager so the xpath queries will work
                Regex ns_rx = new Regex(
                    @"xmlns\s{0,}=\s{0,}""([\w\d\.\:\/\\]{0,})""",
                    RegexOptions.Multiline | RegexOptions.IgnoreCase);
                Match ns_m = ns_rx.Match(m_xml_doc.InnerXml);

                // add the default namespace
                string default_ns = ns_m.Groups[1].Value;
                m_namespace_mgr.AddNamespace("d", default_ns);              
            }
            catch
            {
                xr.Close();
                throw;
            }
        }
    }
}

Regards,
Megha
By Perry    Popularity  (2115 Views)