This code fragment converts a .Net DataTable into an XML Element by
iterating through the Rows and Columns, building up elements for each
row. It then returns them as an XML element called results.
Imports System.XML
...
Private Function TableToElem(ByVal objTable As DataTable) As XmlElement
Dim objDOM As XmlDocument = New XmlDocument
Dim objRoot As XmlElement = objDOM.CreateElement("results")
Dim objRow As DataRow
Dim objElem As XmlElement
Dim lngPos As Integer
Dim objCol As DataColumn
' iterate table contents
For Each objRow In objTable.Rows
objElem = objDOM.CreateElement("row")
' iterate columns
For Each objCol In objTable.Columns
If Not objRow.IsNull(objCol.ColumnName) Then
objElem.SetAttribute(objCol.ColumnName, objRow.Item(objCol.ColumnName))
Else
objElem.SetAttribute(objCol.ColumnName, "")
End If
Next
objRoot.AppendChild(objElem)
Next
Return objRoot
End Function
The returned structure looks like this...
<results rows="5"> <row col1="val1" col2="val2" col3="val3" /> <row col1="val1" col2="val2" col3="val3" /> <row col1="val1" col2="val2" col3="val3" /> <row col1="val1" col2="val2" col3="val3" /> <row col1="val1" col2="val2" col3="val3" /> </results>
243 comments,
VB.Net, Friday, September 10, 2004 12:45


