System.XML - How to Serialize a DataTable to XML Document

Recently I was asked to write a web service that would expose Dynamics GP tables. I've got code to grab the data and populate a DataTable, but I was missing the 'serialize' piece

This short code example will show how to take a DataTable and serialize it into a String.  

    Function SerializeDatatable(ByVal oDT As DataTableByVal strDataTableName As StringAs String
        'declare objects
        Dim mem As New MemoryStream
        Dim settings As New XmlWriterSettings
        settings.Encoding = New UTF8Encoding(False)
        Dim tw As New XmlTextWriter(mem, Encoding.UTF8)
 
        'name the datatable and dataset. 
        'this will cause the XML to generate like this:
        '<?xml version="1.0" encoding="utf-16"?>
        '<Root>
        '    <strDataTableName>
        oDT.TableName = strDataTableName
        oDT.DataSet.DataSetName = "Root"
 
        'initialize
        tw.Formatting = Formatting.Indented
 
        'start the document
        tw.WriteStartDocument()
 
        'insert the datatable
        oDT.WriteXml(tw)
 
        'close the document
        tw.WriteEndDocument()
        tw.Flush()
        tw.Close()
        Dim result As String = Encoding.UTF8.GetString(mem.ToArray())
 
        Return result
 
    End Function

RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences