XML Literals: Reading an XML File
In a prior post here, I created an XML file using VB 9 (Visual Basic 2008/.NET Framework 3.5). This post demonstrates how to read that file and reconstitute the list of customers.
This code reads the XML into an XElement:
Dim customerXml As XElement = XElement.Load("customers.xml")
This code processes the XML and rebuilds the list of customers:
‘ Repopulate the business objects
Dim customerList as New List(Of Customer)
For Each c As XElement In customerXml…<customer>
customerList.Add(New Customer With _
{.LastName = c.<LastName>.Value, _
.FirstName = c.<FirstName>.Value})
Next
The first line of code defines the list that will contain the set of customer objects. The For/Each loop processes each <customer> element. For each element, a new Customer is created using the new object initializer feature in VB 9. The <LastName> and <FirstName> XML elements are read into the LastName and FirstName properties of the new customer. The new customer is then added to the list.
If all goes well, you should end up with the same list that we started with here.
This is almost too easy! 🙂
Enjoy!