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 :


Input XML:

<?xml version="1.0" encoding="utf-8" ?> Delhi Mumbai Hyderabad Sydney Hobart Canberra Toronto Niagara Victoria Dallas Washington Chicago

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 { } }