How to read XML file in VB.NET

Suppose that the user has to read the XML file he/she already generated. The application should provide functionality to extract all vendors from Canada, and after that the user has to process them in alphabetic order.

C# in Depth, 3rd EditionManaged Windows VPS Hosting

 

Web developer has to follow these steps:

   1.Create the XDocument using the XML.
   2.Navigate the XElement elements to reach the Vendor ones.
   3.Take the XElement instances that have a child XElement whose name is Country and whose value is Canada.

The following VB.NET code lines illustrate how to perform filtering

Dim mydoc = XDocument.Load(path)
Dim canada = mydoc.Root.Elements(“Vendor”)
   Where(Function(c) c.Element(“Country”).Value = “Canada”)
   Select(Function(c)
      New With {
         .Name = c.Element(“Name”).Value,
         .Country = c.Element(“Country”).Value
      }
   )

The Root property of the XDocument object represents the root node, and the Elements property gives access to the children of the root (Vendor). Web developer then filters them using a lambda expression. Note: The lambda expression code isn’t strongly typed because Web developer is working with XML, which is a loose-typed data format.

The next VB.NET code lines show how to sort Vendors by name, using the OrderBy method:

Dim sorted = mydoc.Root.Elements(“Vendor”)
   OrderBy(Function(c) c.Element(“Name”).Value)
   Select(Function(c) New With {
     .Name = c.Element(“Name”).Value,
     .Country = c.Element(“Country”).Value
   })