XML Literals: Reading an XML File II
Posted
Tue, Aug 31 2010 22:42
by
Deborah Kurata
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:
Enjoy!