Saturday, 6 April 2013

Message Read from XML

In this post I will show how to read and show message from XML file.

First we will create an XML file in which we will put all the messages.

<main>
  <Validation>
    <label id="REQUSERNAME" text="Username is Required"/>
    <label id="REQPASSWORD" text="Password is Required"/>  
  </Validation>
</main>


Now add the following create class Messages in your project


using System.Xml;
using System.Web.Hosting;

/// <summary>
    /// To Read Error Message from XML file
    /// </summary>
    public class Messages
    {
        #region Properties
        public List<Message> ListMessage { get; set; }
        #endregion

        #region Method
        /// <summary>
        /// Get List of Message for Perticular Module
        /// </summary>
        /// <param name="ModuleName"></param>
        /// <returns>List of Message</returns>
        public string GetMessage(string ModuleName, string MessageId)
        {
            try
            {
                XmlDocument xml = new XmlDocument();
                ListMessage = new List<Message>();

                xml.Load(HostingEnvironment.MapPath("~/Common/Message.xml"));
                XmlNodeList xmlList = xml.SelectNodes("/main/" + ModuleName + "/label");

                foreach (XmlNode lable in xmlList)
                {
                    Message objMessage = new Message();
                    objMessage.ID = lable.Attributes["id"].Value;
                    objMessage.MessageString = lable.Attributes["text"].Value;
                    ListMessage.Add(objMessage);
                }
                string Message = ListMessage.SingleOrDefault(t => t.ID == MessageId).MessageString;
                return Message;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

    }

    /// <summary>
    /// To Get List of Message in ID and Message Structure.
    /// </summary>
    public class Message
    {
        public string ID { get; set; }
        public string MessageString { get; set; }
    }



Now create the object of the class in code behind page and call which message you like to fetch.

Messages msg = new Messages();
rqUserName.ErrorMessage = msg.GetMessage("Validation", "REQUSERNAME");
rqPassword.ErrorMessage = msg.GetMessage("Validation", "REQPASSWORD");


if you have any doubt put comment...

No comments:

Post a Comment