Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Deserialize XML using C#

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 441
    Comment on it

    "How to Deserialize XML document in C#"

        In this article I have discussed about how to deserialize the XML using C#.

    Let us take a simple example to understand better:

    <AddressDetails>
      <HouseNo>4</HouseNo>
      <StreetName>Rohini</StreetName>
      <City>Delhi</City>
    </AddressDetails>
    

    This is the XML that has to be deserialized.

      Inorder to deserialize the XML we need to create a class, having variable with same name as that of XML tags.
    The values of the XML tags get mapped to their corresponding variable, during desrialization.

     So for the above XML following is the corresponding class:

    public class Address
    {
        public int HouseNo { get; set; }
        public string StreetName { get; set; }
        public string City { get; set; }
    }
    

    Now following is the code packet that will actually map this XML to the class object:

    public static void Main(string[] args)
    {
        XmlSerializer deserializer = new XmlSerializer(typeof(Address));
        TextReader reader = new StreamReader(@"D:\myXml.xml"); // path where the XML is stored
        object obj = deserializer.Deserialize(reader);
        Address XmlData = (Address)obj;
        reader.Close();
    }
    

    Now as we have actually deserialized the XML we can access the XML tag values by:

    Address.HouseNo,
    Address.StreetName,
    Address.City
    

    Hope this helps you... Happy Coding..!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: