Reading XML tag Values using Programmatically

Get the XML tag values 

1. Create Constants.xml file and create the tags in the below format.

<?xml version="1.0" encoding="utf-8" ?>
<ConstantsXML>  //This is used as identifier to read the data from inside of the identified tag from Code
<Constants>
<EmpName>Employee Name</EmpName>
<EmployeeID>Employee Id</EmployeeID>
<EmpDepartment>Department</EmpDepartment>
</Constants>
</ConstantsXML>

2. Declaring the Variables

  #region Members

        static String elementValue;
        private static readonly String ConstantNodeIdentifier = "ConstantsXML";
        private static XDocument m_sourceDocument;

  #endregion

3. Method to Read the XML Document form the Specified Path

static Constant()
        {
            try
            {
                if (System.IO.File.Exists(HostingEnvironment.MapPath("~/Common/Configuration.xml")))
                {
                    m_sourceDocument = XDocument.Load(HostingEnvironment.MapPath("~/Common/Configuration.xml")); //XDocument calls the Step four to read the data from the XML File
                }
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
        }

4.  To Read the XML Document data.

 static XDocument LoadFromStream(Stream stream)
        {
            try
            {
                using (XmlReader reader = XmlReader.Create(stream))
                {
                    return XDocument.Load(reader);
                }
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }

        }

5. Main the Function to return the XML tag data  to the called function and store it in a variable


        /// <summary>
        /// Get the Constants from xml file 
        /// </summary>
        /// <param name="formName">formname</param>
        /// <param name="keyName">ElementName</param>
        /// <returns>ElementValue</returns>
        public static String GetElementValue(String formName, String keyName)
        {
            try
            {
                if (m_sourceDocument != null)
                {
                    elementValue = m_sourceDocument.Element(ConstantNodeIdentifier).Element(formName).Element(keyName).Value;
                }
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            return elementValue;

        }

6. Declare the variables to get the data from the XML tag

static String xmlEmpName = GetElementValue("Constants", "EmpName");




Comments

Popular posts from this blog

SharePoint 2013 Keyword Query (KQL) Content Class Property Restrictions

Filtering the Sharepoint List Taxonomy Column using Rest API

Hide Save button in New and Edit form in SharePoint 2013 list