Using LINQ to Read Xml Instead of XmlDocument

If you are interested in using LINQ to read Xml instead of the older way of the XmlDocument and SelectNodes, the code below is a pretty good example. The code takes in the ISO standard file for country names and codes (see sample below) and turn it into a list of Country objects for use in an application including ComboBoxes.

<?xml version=1.0 encoding=ISO-8859-1 standalone=yes?>

<ISO_3166-1_List_en xml:lang=en>

   <ISO_3166-1_Entry>

      <ISO_3166-1_Country_name>AFGHANISTAN</ISO_3166-1_Country_name>

      <ISO_3166-1_Alpha-2_Code_element>AF</ISO_3166-1_Alpha-2_Code_element>

   </ISO_3166-1_Entry>

   <ISO_3166-1_Entry>

      <ISO_3166-1_Country_name>ÅLAND ISLANDS</ISO_3166-1_Country_name>

      <ISO_3166-1_Alpha-2_Code_element>AX</ISO_3166-1_Alpha-2_Code_element>

   </ISO_3166-1_Entry>

</ISO_3166-1_List_en>

Before

Here is the original code that has been in use for a few years. It uses the “easy” way of loading and selecting nodes using the XmlDocument object.

Dim countriesXml As New System.Xml.XmlDocument

countriesXml.LoadXml(My.Resources.CountriesXML)

 

Dim list As New System.Collections.Generic.List(Of Country)

 

For Each country As System.Xml.XmlNode In countriesXml.SelectNodes(“//ISO_3166-1_Entry”)

 

   Dim tempCountry As New Country

 

   tempCountry.Name = country.SelectSingleNode(“ISO_3166-1_Country_name”).InnerText

   tempCountry.Code = country.SelectSingleNode(“ISO_3166-1_Alpha-2_Code_element”).InnerText

 

   list.Add(tempCountry)

 

Next

 

After

This code uses LINQ and the new XElement to make it easy to load the xml from the assemblies resources.

Dim reader = XElement.Parse(My.Resources.Countries)

 

Dim list As New System.Collections.Generic.List(Of Country)

 

Dim data = From c In reader.Elements(XName.Get(“ISO_3166-1_Entry”)) _

           Order By c.Element(XName.Get(“ISO_3166-1_Country_name”)).Value _

           Select New Country With {.Name = c.Element(XName.Get(“ISO_3166-1_Country_name”)).Value, _

                            .Code = c.Element(XName.Get(“ISO_3166-1_Alpha-2_Code_element”)).Value.ToUpper}

 

As you can see this is much cleaner, fewer lines of code and actually faster (1 millisecond). Also you can see in the Select line that I am actually filling the Country object during the query… pretty cool!

Tip Submitted By: David McCarter

This code can be found in the open source dotNetTips.Utility assembly


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.