Easing into XML - An easy way to work with XML, Datasets, and .NET
.Net has a lot of built in support for XML as a data structure, and they provde some pretty direct methods to traverse nodes and attributtes with XML. However, especially as of late, I've been sharing data to-from other applications via XML. During this process, sometimes I just want to get at the data... I don't want to loop through any nodes, I just want my data... either to throw at a datagrid, or perhaps just to check a value of something. Additionally, I already have my XML data sitting in a string, its not saved anywhere in a file, it's already accessible in my application.
In my travels, I was able to eventually figure out this formula for success. It accepts a string of XML (properly formed... of course) and reads it into a dataset, which in turn is read into a datatable, which in turn can be accessed via a datarow.
'I know it wont exactly win any awards, but here's some sample XML
Dim xmlText As String = "<OurData><customerID>08459684</customerID></OurData>"
'a datatable to hold our data
Dim dt As New DataTable
'a dataset to convert our xml into a datatable
Dim ds As New DataSet
'a datarow to read our datatable
Dim dr As DataRow
'Datasets can read XML in via a StringReader. If we already have our XML, and
'its not being provided to us via an external document, we can create a new
'StringReader on the fly, supplying our XML when it is instantiated
ds.ReadXml(New System.IO.StringReader(xmlText))
'Now that we have a dataset, use our datatable to receive our "table", which
'in this case is "OurData" based on the sample XML above
dt = ds.Tables(0)
'Now we can read in any "rows" from our XML. We only have one row, so I'll
'for-go writing any logic to loop through the rows...
dr = dt.Rows(0)
'Finally, we can directly reference our node and get our value based
'on the current row
Dim custID as String = CStr(dr.Item("customerID"))
Yes... it IS that simple...


0 Comments:
Post a Comment
<< Home