blog

Home / DeveloperSection / Blogs / Reading XML from LINQ

Reading XML from LINQ

Sumit Kesarwani4250 19-Dec-2013

In this blog, I’m explaining how to read the xml from linq query.

Example In this example, we will have two combo boxes – country and city and we will populate these combo boxes from xml file using linq query and also change the cities in city combo box according to country combo box value.

Step 1:

First create a windows form application and add two combo box one for country and other for city like this:

Reading XML from LINQ

Step 2:

Now create a xml file and save with “cities.xml” name:

<?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>

Step 3:

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.

Now write the below code in the from load event:

XDocument xdoc = XDocument.Load(“Your xml file path”); //load the xml file
var countries = from country in xdoc.Descendants("countries").Elements("country").Attributes("name")
                            select country.Value; //Get all country from xml
cbCountry.DataSource = countries.ToList();//Populate country combo box with countries
var cities = from country in xdoc.Descendants("countries").Elements("country")
                         where country.Attribute("name").Value == cbCountry.SelectedValue.ToString()
                         from city in country.Elements("city")
                         orderby city.Value
                         select city.Value; //Get the cities from xml
cbCity.DataSource = cities.ToList();//Populate city combo box with cities

Step 4:

Now write the below code in the selected index changed event of country combo box:

XDocument xdoc = XDocument.Load(“Your xml file path”);
var cities = from country in xdoc.Descendants("countries").Elements("country")
                             where country.Attribute("name").Value == cbCountry.SelectedValue.ToString()
                             from city in country.Elements("city")
                             orderby city.Value
                             select city.Value;//Get cities according to the country currently selected in country combo box
cbCity.DataSource = cities.ToList();

This linq query will populate the city combo box with cities according to


the country selected in the country combo box.

Output

Reading XML from LINQ

Updated 18-Sep-2014

Leave Comment

Comments

Liked By