Menu ▼

Previous Next

Reading XML using LINQ :

By using XDocument object we can load XML documents, Writing linq queries on XDocument will return collection. In linq query xdocument.Descendants will return a IEnumarable XElement collection.

Lets take an example XML file which conatins country and city list.
Take two dropdown lists, the first one has to be filled with counties list by reading xml. And when user select country from the dropdown, get the cities list in that country from the xml and bind it to second dropdown.

Example :   Country :   City :


Input XML :

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

<countries>

  <country name='India'>

    <city>Delhi</city>

    <city>Mumbai</city>

    <city>Hyderabad</city>

  </country>

  <country name='Australia'>

    <city>Sydney</city>

    <city>Hobart</city>

    <city>Canberra</city>

  </country>

  <country name='Canada'>

    <city>Toronto</city>

    <city>Niagara</city>

    <city>Victoria</city>

  </country>

  <country name='USA'>

    <city>Dallas</city>

    <city>Washington</city>

    <city>Chicago</city>

  </country>

</countries>


LINQ Code :

In PageLoad :

XDocument xdoc = XDocument.Load("D:\\countries.xml");

var countires = from country in xdoc.Descendants("countries").Elements("country").Attributes("name")

                select country.Value;

ddlCountry.DataSource = countires;

ddlCountry.DataBind();

 

var cities = from country in xdoc.Descendants("countries").Elements("country")

                where country.Attribute("name").Value == ddlCountry.SelectedValue

                from city in country.Elements("city")

                orderby city.Value

                select city.Value;

 

ddlCity.DataSource = cities;

ddlCity.DataBind();

 

In ddlCountry SelectedIndexChanged :

protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)

{

    try

    {

        XDocument xdoc = XDocument.Load("D:\\countries.xml");

        var cities = from country in xdoc.Descendants("countries").Elements("country")

                        where country.Attribute("name").Value == ddlCountry.SelectedValue

                        from city in country.Elements("city")

                        orderby city.Value

                        select city.Value;

 

        ddlCity.DataSource = cities;

        ddlCity.DataBind();

    }

    catch

    {

    }

}

Previous Next




Search dotnetlearners.com