Hi I have a datatable which i can save easily as xml using the following code.

My problem is that i also have a textbox which i would like to save with this datatable. How can i save a datatable + textbox value as one XML file.

Many thank for you replys.

   Dim di As DirectoryInfo = New DirectoryInfo("C:\Test")


        With SaveFileDialog1

            .InitialDirectory = "C:\Test"
            .FileName = ""
            .Filter = "Text files (*.txt)|*.txt|" & "All files|*.*"
            If .ShowDialog() = DialogResult.OK Then
                Dim FileName As String = .FileName

                dt.TableName = "MainData"


            End If

        End With

I think this pattern should work for you. I'm still learning this XML stuff.

   ' create a named datatable
   ' content is irrelevant
   Dim dt As New DataTable("fredsfamily")
   Dim r As DataRow
   With dt
      r = .NewRow : r(0) = "wilma" : .Rows.Add(r)
      r = .NewRow : r(0) = "pebbles" : .Rows.Add(r)
   End With

   ' Instead of writing directly to a file
   ' write to a stringbuilder

   Dim sb As New System.Text.StringBuilder(500)
   Dim writer As New IO.StringWriter(sb)

   ' make sure you include the schema definition and not just the data
   dt.WriteXml(writer, XmlWriteMode.WriteSchema)

   ' Now the we have the Table XML in the stringbuilder
   ' create a XmlDocument and load it from the stringbuilder
   Dim doc As New Xml.XmlDocument()

   ' Now we can modify the documents content
   ' I adding a CDataSection to hold the text
   Dim el As Xml.XmlCDataSection = doc.CreateCDataSection(tbSomething.Text)

   doc.Save("test.xml") ' Now write it to a file

   ' *** Now to reverse the process and read the XML file
   tbSomething.Text = String.Empty

   ' The DataTable is easy.
   Dim dt2 As New DataTable

   dt2.ReadXml("test.xml") ' that is it :)

   ' The to retrieve the text we embedded in the file
   'I'm using the Xml.Linq stuff for this as it is a bit easier to code than XPath stuff
   ' Load a document
   Dim doc2 As System.Xml.Linq.XDocument = XDocument.Load("test.xml")
   ' Since we have only one CData
   Dim cdatalist As List(Of Xml.Linq.XCData) = doc2.DescendantNodes.OfType(Of XCData)().ToList()
   ' We should have retrieved 1 CData section into our list
   If cdatalist.Count > 0 Then tbSomething.Text = cdatalist.Item(0).Value
This article has been dead for over six months. Start a new discussion instead.