Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all articles
Browse latest Browse all 27569

VS 2010 Serialize and deserialize structure data to-from XML

$
0
0
Hello,
I need to serialize and deserialize data to-from XML.
This seem's work OK.

Code:

    Public Function structToXML(ByVal obj As Object) As String

        Dim x As New Xml.Serialization.XmlSerializer(obj.GetType())
        Dim sw As New StringWriter()
        x.Serialize(sw, obj)
        Return sw.ToString
    End Function

So I can pack my structure data to XML string:
Code:

<Serializable()> _
Public Structure myStruct
    Dim first As Integer
    Dim second As String
    Dim third As Double
End Structure
...

        Dim p As New myStruct
        p.first = 1
        p.second = "abcde"
        p.third = 3.14
        Dim xmlstr As String = structToXML(p)

With that I get valid XML string (xmlstr).

Now I have function to fill structure data from same xmlstr which also look's good and passes without any reported errors but I don't know to call it properly or didn't make arguments properly:
Code:

    Public Function XMLToStruct(ByVal xString As String, ByVal type As Type) As Object

        Dim x As New Xml.Serialization.XmlSerializer(type)
        Dim sw As New IO.StringReader(xString)
        Return x.Deserialize(sw)
    End Function

I am try like that:
Code:


'Set new data to structure

        p.first = 2
        p.second = "fghi"
        p.third = 7.64

'Load old data to structure myStruct, instance p
      p = XMLToStruct(xmlstr, GetType(myStruct))

Here I get error: Option Strict On disallows implicit conversions from 'Object' to 'myproj.myStruct'.
Of course, I woud like to keep Option Strict = On.

What I am doing wrong and how to easiest to get data to p from xmlstr by using XMLToStruct function?
Or it is needed to do some changes in function or what?

Viewing all articles
Browse latest Browse all 27569

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>