Mar
15
Written by:
Steve Gray
3/15/2011 3:27 PM
This code sample will show you how to take an XML document and parse it into VB elements (in this example I use a class)
First create the class:
Code Snippet
- Public Class Item
- Public Property itemnmbr As String
- Public Property itemguid As Guid
- Public Property active As String
- Public Property description As String
- Public Property category As String
- Public Property commissionamt As Double
- Public Property listprice As Double
- Public Property reorderpt As Int32
-
- End Class
This code will take the XML document shown are read it into the class. You’d want a Generic Collection of this class to get all the items, I’m going for simplicity here as much as possible
Code Snippet
- Dim xDoc As XDocument
- Dim xElem As XElement
-
- xElem = <items>
- <item guid="6A639774-5EA9-440C-978B-FDC7DBF71949">
- <SKUid>AAA001</SKUid>
- <active>Y</active>
- <description>SD128 RAM</description>
- <category>Electronics</category>
- <commissionamt>0.00</commissionamt>
- <listprice>9.99</listprice>
- <reorderpt>1</reorderpt>
- </item>
- <item guid="D8FD406F-8CF2-47E6-B09D-E44106153C11">
- <SKUid>AAA02</SKUid>
- <active>Y</active>
- <description>SD256 RAM</description>
- <category>Electronics</category>
- <commissionamt>0.00</commissionamt>
- <listprice>19.99</listprice>
- <reorderpt>5</reorderpt>
- </item>
- </items>
-
- xDoc = XDocument.Parse(xElem.ToString)
-
- Dim childElements As IEnumerable(Of XElement)
-
- childElements = _
- From el In xDoc.<items>.Elements() _
- Select el
-
- For Each el As XElement In childElements
- oItem = New Item
- oItem.itemguid = New Guid(el.@guid)
- oItem.itemnmbr = el.<SKUid>.Value
- oItem.active = el.<active>.Value
- oItem.description = el.<description>.Value
- oItem.category = el.<category>.Value
- oItem.commissionamt = el.<commissionamt>.Value
- oItem.listprice = el.<listprice>.Value
- oItem.reorderpt = el.<reorderpt>.Value
- Next
As always, I welcome your comments!