When you serialize a dataset, an XML document is created containing the data (everyone knows this, right?) I just recently did some investigation on the string that gets created for a serialized dataset... Dang! It contains a lot more info than I thought. The reason is that it contains the XML Schema plus the data that is contained in the rows. For copying the data from a query into session, viewstate, or the cache (so that you can re-use the data later), this is way overkill.
So I had already come up with a better way (doing some caching of data via files). The dataset also has two methods called ReadXML and WriteXML. You can use these to create an XML string that contains simply the data. So here's the code (sorry for the lack of vb colors):
Option Strict On
Imports System.Xml
Imports System.Data
Imports System.Text
Public Class DataSet_Serializaion
Public Shared Function SmartSerialize(ByVal ds As DataSet) As String
Dim __ms As System.IO.MemoryStream
Dim __dcod As Decoder
Dim __chars() As Char
Try
__ms = New System.IO.MemoryStream
__dcod = Encoding.UTF8.GetDecoder()
ds.WriteXml(__ms)
ReDim __chars(CInt(__ms.Length))
__dcod.GetChars(__ms.GetBuffer(), 0, CInt(__ms.Length), __chars, 0)
Return New String(__chars)
Finally
If Not (__ms Is Nothing) Then
__ms.Close()
__ms = Nothing
End If
__dcod = Nothing
End Try
End Function
Public Shared Function SmartDeSerialize(ByVal serialized As String) As DataSet
Dim __ds As DataSet
' needed to create an XML TextReader
Dim nt As NameTable
Dim nsmgr As XmlNamespaceManager
Dim context As XmlParserContext
Dim tr As XmlTextReader
Try
__ds = New DataSet
nt = New NameTable
nsmgr = New XmlNamespaceManager(nt)
context = New XmlParserContext(Nothing, nsmgr, Nothing, XmlSpace.None)
tr = New XmlTextReader(serialized, XmlNodeType.Document, context)
__ds.ReadXml(tr)
Return __ds
Finally
If Not (tr Is Nothing) Then
tr.Close()
tr = Nothing
End If
context = Nothing
nsmgr = Nothing
nt = Nothing
End Try
End Function
End Class
(CODE NOTE: I had problems using the memory stream for input so I used a generic textreader instead).
Anyway, this will produce an XML representation of just the data behind the dataset. I would say that you would want to use this one for datasets containing data with no relationships. I would avoid the use of the above method for data that you are updating (in other words, don't use this for datasets that you intend to use for batch updates).
This example works pretty good... I would still like to add some of the stuff that Carl Franklin's did in his CarlsZipLibrary located here.
(Wow, post #6... I'm almost somebody.. hahaha)
Print | posted on Tuesday, March 30, 2004 3:03 PM