How to Read From XML Document

Many times we have a scenario like we need to use some hardcode values like our SQL connection string or some List name or any configuration settings like network credentials.

All these information is sensitive and there are chances that after sometimes we need to change these network credentials, or network path due to some unavoidable reasons. So if we have all these things in our .cs file than for changing this information we need to rebuild our dll.

To avoid these kinds of situations we are using a XML configuration file. In this article I am going to show how to read a xml file.

Step1: Make one XML file and name it XML_Configuration_File.xml and place it in C:\Test\ location. The configuration file should look in the format as shown in below.

<Configuration>
  <
FName>Jack</FName>
  <SName>Sparrow</SName>
</Configuration>

Configuration is the Parent node and FName, SName are the Child nodes.

Step2: Open visual studio and make a console application project.
Step3: For making any operation on XML file we need to add reference of System.XML
Step4: Code for reading XML file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace ReadFromXML
{
    class Program
    {
        private const string sXML_File_Path = @"C:\Test\XML_Configuration_File.xml";
        static void Main(string[] args)
        {
            string sFirstName = GetXmlConfigValue("FName");
            string sSecondName = GetXmlConfigValue("SName");
            Console.WriteLine(sFirstName + " " + sSecondName);
            Console.Read();
        }

        public static string GetXmlConfigValue(string sNodeName)
        {
            string sNodeValue = "";
            XmlDocument xml_Document = null;
            XmlNodeList xnlNodelist = null;
            XmlNode xnParent = null;
            XmlNode xnChild = null;

        xml_Document = new System.Xml.XmlDocument();
        try
        {
            //Load the XML document
            xml_Document.Load(sXML_File_Path);

            //Find the node by Tagname which should be exactle same as in our XML Configuration
file.
            xnlNodelist = xml_Document.GetElementsByTagName(sNodeName);
 
            //Point to parent node from the Node List(In our example Configuration is the Parent Node.
            xnParent = xnlNodelist.Item(0);
 
            //Point to Child node.
            xnChild = xnParent.ChildNodes[0];

            //Read the value from the child node.
            sNodeValue = xnChild.InnerText.ToString();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return sNodeValue;     
  
     }

       }
}

When we execute the program we will get the output in the below format:

XML.gif

In this way we can read a xml file.

Thank You!

Ravish


Similar Articles