Deborah's Developer MindScape

         Tips and Techniques for Web and .NET developers.

September 1, 2010

XML Literals: Reading an XML File II

Filed under: VB.NET,XML @ 12:42 am

This series of posts covers more information on using XML literals. Since XML Literals are a VB.NET feature only (new in VB 9/VS 2008), these posts will only include VB.NET code.

The scenario is that we were given an XML file, maybe from a Web service or from an external application. The code needs to read and process the information in the file. In this case the task is to read the customer names and concatenate them. The results could be displayed in a control such as a ListBox or added to a database or written to another XML file.

So here is the XML in a file named CustomerInfo.xml:

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

Here is the code in VB.NET:

Dim xmlDoc = XDocument.Load("CustomerInfo.xml")
Dim fullName As String

For Each custXML In xmlDoc…<Customer>
    fullName = custXML…<LastName>.Value & ", " &

This code first loads the xml from the XML file using the Load method from the XDocument class. It then loops through all of the Customer elements.

The ellipsis (…) means "descendant", so xmlDoc…<Customer> finds all Customer elements that are descendants of root node. Similarly, custXML…<LastName> finds the descendant element of Customer named LastName and so on.

The result in the Debug Window is as follows:

Baggins, Bilbo
Baggins, Frodo
Gamgee, Sam

Use this technique any time you need to read data from an XML file.

For more information, click on one of the following links:



  1.   Chris Madsen — September 1, 2010 @ 4:09 pm    Reply

    You use a variable custXML without defining it. How is it defined?

    Also, for us laggards, it would nice if you could mention which versions of .NET things work in.

  2.   DeborahK — September 2, 2010 @ 12:31 am    Reply

    Hi Chris –

    I will fix the post and include the VB version. Regarding the custXml, I define it as part of the ForEach statement. I just don’t have an As clause because I am using implicit typing.

    With an As clause, it would look like this:

    For Each custXML As XElement In … 

    Thanks for your comments!

  3.   Nuryus — November 28, 2012 @ 12:27 am    Reply

    Imrpssevie brain power at work! Great answer!

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2021 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs