How I do serialize the data table into XML?

SILS 61 Reputation points
2022-12-22T04:28:29.607+00:00

Hi.
I have an issue while to try convert data table into XML format
Error is "Cannot serialize the DataTable. DataTable name is not set".

What I tried is below

    Public Function ConvertDatatableToXML(ByVal dt As DataTable) As String  
        Dim str As MemoryStream = New MemoryStream()  
        dt.WriteXml(str, True)  
        str.Seek(0, SeekOrigin.Begin)  
        Dim sr As StreamReader = New StreamReader(str)  
        Dim xmlstr As String  
        xmlstr = sr.ReadToEnd()  
        Return (xmlstr)  
    End Function   
  
    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click  
        Dim dt As DataTable = New DataTable()  
        dt = GetData()  
        Dim XMLstring As String = clsAPI.ConvertDatatableToXML(dt)  
        Me.txtComments.Text = XMLstring  
  
    End Sub  
  
   Public Function GetData() As DataTable  
        Dim dt As New DataTable  
        Dim adp As New SqlDataAdapter("usp_TR_Data", conn)  
        adp.SelectCommand.CommandType = CommandType.StoredProcedure  
        adp.SelectCommand.CommandTimeout = 150  
  
        With adp.SelectCommand.Parameters  
            .Clear()  
            .Add("@Action", SqlDbType.NVarChar).Value = "CONVERT-XML"  
            .Add("@SONo", SqlDbType.NVarChar).Value = Me.txtSONo.Text  
        End With  
        adp.Fill(dt)  
        Return dt  
    End Function  
  
  
  
SQL Query  
		Select   
			[sname],[saddress1],[saddress2],[scity],[spostcode],[sstate],  
			[dairport],[scountry],	[detailOfContent],[weight],[productPackages],  
			[dimensionX],[dimensionY],[dimensionZ],[chargeableRate],[rname],[rphone],  
			[raddress1],[raddress2],[rpostcode],[rcity],[rstate],[rairport],[rcountry],  
			[rremark],[rvia],[serviceModeId],[agentId],[trackingno]  
		From TR_Data  
		where SONo=@sono  
SQL Server | Other
0 comments No comments
{count} votes

Accepted answer
  1. Marian Leica 536 Reputation points Microsoft Employee
    2022-12-22T08:00:09.627+00:00

    Hi,
    The error message "Cannot serialize the DataTable. DataTable name is not set" is saying that the TableName property of the DataTable object is not set. Please try to set the TableName property of the DataTable object before calling the WriteXml method. Something like:

    dt.TableName = "YourTableName"  
    

    or by adding the table name on the function as an argument, like:

    dt.WriteXml(str, True, "YourTableName")  
    

    Let us know how it goes.
    If the above response was helpful, please feel free to "Accept as Answer" and "Upvote" so it can be beneficial to the community.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.