XML Literals: Reading an XML File II
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" ?>
<Customers>
<Customer>
<LastName>Baggins</LastName>
<FirstName>Bilbo</FirstName>
</Customer>
<Customer>
<LastName>Baggins</LastName>
<FirstName>Frodo</FirstName>
</Customer>
<Customer>
<LastName>Gamgee</LastName>
<FirstName>Sam</FirstName>
</Customer>
</Customers>
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 & ", " &
custXML…<FirstName>.Value
Debug.WriteLine(fullName)
Next
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:
- But what if the XML file includes a defined namespace?
- But what if the XML file’s namespace can not be "hard-coded"?
- But what if I need to create XML?
- But what if I need to create XML that includes a defined namespace?
- But what if I need to create XML that includes a namespace that can not be "hard-coded"?
Enjoy!
Chris Madsen — September 1, 2010 @ 4:09 pm
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.
DeborahK — September 2, 2010 @ 12:31 am
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!
Nuryus — November 28, 2012 @ 12:27 am
Imrpssevie brain power at work! Great answer!