Jitesh Byahut 6/23/2014 2345

How To Read Xml In C#

Use System.Xml.Linq Namespace.

Here a example is shown to how to read different types of xml documents.

<?xml version="1.0" encoding="utf-8" standalone="yes"?>

<Students>

  <Student Id="1">

    <Name>Jitesh</Name>

    <Email>jitesh@asphelps.com</Email>

    <City>Buxar</City>

  </Student>

  <Student Id="2">

    <Name>Amit</Name>

    <Email>Amit@asphelps.com</Email>

    <City>Dumraon</City>

  </Student>

</Students>

XDocument document = XDocument.Load(@"D:\Student1.xml");


bool IsExist = document.Descendants("Student").Where(i => i.Attribute("Id").Value == "1").Select(i => i).Any();

        // Output

        // true

string name = document.Descendants("Student").Where(i => i.Attribute("Id").Value == "1")

                      .Select(i => i.Element("Name").Value).Single();

        // Output

        // Jitesh

    class Student

    {

        public string ID { get; set; }

        public string Name { get; set; }

        public string Email { get; set; }

        public string City { get; set; }

    }

Student objStud = document.Descendants("Student")

            .Where(i => i.Attribute("Id").Value == "1").Select(

            x => new Student

            {

                ID = x.Attribute("Id").Value,

                Name = x.Element("Name").Value,

                Email = x.Element("Email").Value,

                City = x.Element("City").Value

            }).Single();

 

        Response.Write(objStud.ID);

        Response.Write(objStud.Name);

        Response.Write(objStud.Email);

        Response.Write(objStud.City);

        // Output:

        // 1

        // Jitesh

        // jitesh@asphelps.com

        // Buxar

List<Student> listStud = document.Descendants("Student").Select(

            x => new Student

            {

                ID = x.Attribute("Id").Value,

                Name = x.Element("Name").Value,

                Email = x.Element("Email").Value,

                City = x.Element("City").Value

            }).ToList();

 

        foreach (Student student in listStud)

        {

            Response.Write(student.ID);

            Response.Write(student.Name);

            Response.Write(student.Email);

            Response.Write(student.City);

            Response.Write("-----------");

        }

        // Output:

        // 1

        // Jitesh

        // jitesh@asphelps.com

        // Buxar

        //-----------

        // 2

        // Amit

        // Amit@asphelps.com

        // Dumraon

        //-----------



Please give your feedback for improving this page