How to xml serialize arraylist of objects?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Brad

    How to xml serialize arraylist of objects?

    I would like to serialize an arraylist of objects to xml so I can store the
    xml in a database column. How would I code the serializing and
    deserializing? Below is a (overly) simple, incomplete example of what I'd
    want to accomplish.

    Thanks
    Brad


    Example
    =============== =============== ===
    ' This object will be used in an arraylist
    Public Class MyObject
    Private _name as string

    Public Property Name as string
    Get
    Return _name as string
    End Get
    Set (ByVal Value)
    _name = Value
    End Set
    End Property
    End Class

    =============== =============== ===
    ' This object will serialize xml for
    Public Class BusLayer
    Public Sub Update
    Dim myList as new ArrayList

    Dim mo1 as new MyObject
    mo1.Name = "Jack"
    myList.Add(mo1)

    Dim mo2 as new MyObject
    mo2.Name = "Jill"
    myList.Add(mo2)

    ' Serializing code. What I've figure out so far but does not
    work.

    Dim mySerializer As New
    System.Xml.Seri alization.XmlSe rializer(GetTyp e(ArrayList))
    Dim strWriter As New StringWriter
    Dim writer As New XmlTextWriter(s trWriter)
    writer.Formatti ng = Formatting.Inde nted
    mySerializer.Se rialize(writer, attributeValues )

    Dim result as string = strWriter.ToStr ing
    ' String xml can now be written to database in stored procedure
    parameter...eas y to do

    End Sub

    Public Sub Read
    Dim dbString as string

    ' Deserializing code here assume dbString already read from database
    ' and needs to be deserialized. How????


    End Sub

    End Class


  • Cor

    #2
    Re: How to xml serialize arraylist of objects?

    Hi Brad,

    What I would do is making a dataset with one table and one column
    Filling that by itterate through that and than say
    dim mystring as string ds.GetXML()
    This gives a simple XML string.

    I did not use this yet and I do not know yet how to deserialize, but that is
    not your question.

    Maybe you can try it,

    I hope this helps?

    Cor[color=blue]
    > I would like to serialize an arraylist of objects to xml so I can store[/color]
    the[color=blue]
    > xml in a database column. How would I code the serializing and
    > deserializing? Below is a (overly) simple, incomplete example of what[/color]
    I'd[color=blue]
    > want to accomplish.[/color]


    Comment

    • Peter Huang

      #3
      RE: How to xml serialize arraylist of objects?

      Hi Brad,

      Thanks for posting in the community.

      First of all, I would like to confirm my understanding of your issue.
      From your description, I understand that you wants to serialize an
      arraylist to a xml file and deserialize ti from the xml.
      Have I fully understood you? If there is anything I misunderstood, please
      feel free to let me know.

      Here I write the code sinippet.

      <code>
      Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
      System.EventArg s) Handles Button1.Click
      Dim objs As New Group
      Dim obj1 As New MyObject
      obj1.Name = "Obj1Name"
      Dim obj2 As New MyObject
      obj2.Name = "Obj2Name"
      objs.Info = New ArrayList
      objs.Info.Add(o bj1)
      objs.Info.Add(o bj2)
      Dim x As XmlSerializer = New XmlSerializer(G etType(Group))
      Dim writer As TextWriter = New StreamWriter("T est.xml")
      x.Serialize(wri ter, objs)
      writer.Close()
      End Sub

      Private Sub Button2_Click(B yVal sender As System.Object, ByVal e As
      System.EventArg s) Handles Button2.Click
      Dim serializer As New XmlSerializer(G etType(Group))
      ' A FileStream is needed to read the XML document.
      Dim fs As New FileStream("Tes t.xml", FileMode.Open)
      Dim reader As New XmlTextReader(f s)
      Dim gp As Group = CType(serialize r.Deserialize(r eader), Group)
      For Each o As MyObject In gp.Info
      MsgBox(o.Name)
      Next
      End Sub

      Public Class Group
      <XmlElement(Typ e:=GetType(MyOb ject))> _
      Public Info As ArrayList
      End Class
      Public Class MyObject
      Private _name As String
      Public Property Name() As String
      Get
      Return _name
      End Get
      Set(ByVal Value As String)
      _name = Value
      End Set
      End Property
      End Class

      </code>


      Also here is some links may help you.
      Controlling XML Serialization Using Attributes
      See section "Serializin g an ArrayList"

      xmlserializerwi thattributes.as px

      Examples of XML Serialization
      See section: Serializing a Class that Implements the ICollection Interface

      nwithxmlseriali zer.aspx

      Please apply my suggestion above and let me know if it helps resolve your
      problem.

      Best regards,

      Peter Huang
      Microsoft Online Partner Support

      Get Secure! - www.microsoft.com/security
      This posting is provided "AS IS" with no warranties, and confers no rights.

      Comment

      • Brad

        #4
        Re: How to xml serialize arraylist of objects?

        Peter, Thank you very much for your reply and for your example.
        Using your example and some further reading of docs to understand I found
        that I could the code would also work without the "Group" object if I
        changed the following in Button1 and Button2:
        From
        New XmlSerializer(G etType(Group))
        To
        New System.Xml.Seri alization.XmlSe rializer(GetTyp e(ArrayList), New
        Type() {GetType(MyObje ct)})

        Is there anything wrong with this alternate approach?

        Thanks

        Brad


        "Peter Huang" <v-phuang@online.m icrosoft.com> wrote in message
        news:bC07akcAEH A.612@cpmsftngx a06.phx.gbl...[color=blue]
        > Hi Brad,
        >
        > Thanks for posting in the community.
        >
        > First of all, I would like to confirm my understanding of your issue.
        > From your description, I understand that you wants to serialize an
        > arraylist to a xml file and deserialize ti from the xml.
        > Have I fully understood you? If there is anything I misunderstood, please
        > feel free to let me know.
        >
        > Here I write the code sinippet.
        >
        > <code>
        > Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
        > System.EventArg s) Handles Button1.Click
        > Dim objs As New Group
        > Dim obj1 As New MyObject
        > obj1.Name = "Obj1Name"
        > Dim obj2 As New MyObject
        > obj2.Name = "Obj2Name"
        > objs.Info = New ArrayList
        > objs.Info.Add(o bj1)
        > objs.Info.Add(o bj2)
        > Dim x As XmlSerializer = New XmlSerializer(G etType(Group))
        > Dim writer As TextWriter = New StreamWriter("T est.xml")
        > x.Serialize(wri ter, objs)
        > writer.Close()
        > End Sub
        >
        > Private Sub Button2_Click(B yVal sender As System.Object, ByVal e As
        > System.EventArg s) Handles Button2.Click
        > Dim serializer As New XmlSerializer(G etType(Group))
        > ' A FileStream is needed to read the XML document.
        > Dim fs As New FileStream("Tes t.xml", FileMode.Open)
        > Dim reader As New XmlTextReader(f s)
        > Dim gp As Group = CType(serialize r.Deserialize(r eader), Group)
        > For Each o As MyObject In gp.Info
        > MsgBox(o.Name)
        > Next
        > End Sub
        >
        > Public Class Group
        > <XmlElement(Typ e:=GetType(MyOb ject))> _
        > Public Info As ArrayList
        > End Class
        > Public Class MyObject
        > Private _name As String
        > Public Property Name() As String
        > Get
        > Return _name
        > End Get
        > Set(ByVal Value As String)
        > _name = Value
        > End Set
        > End Property
        > End Class
        >
        > </code>
        >
        >
        > Also here is some links may help you.
        > Controlling XML Serialization Using Attributes
        > See section "Serializin g an ArrayList"
        >[/color]
        http://longhorn.msdn.microsoft.com/l...erializationby[color=blue]
        > xmlserializerwi thattributes.as px
        >
        > Examples of XML Serialization
        > See section: Serializing a Class that Implements the ICollection Interface
        >[/color]
        http://longhorn.msdn.microsoft.com/l...mlserializatio[color=blue]
        > nwithxmlseriali zer.aspx
        >
        > Please apply my suggestion above and let me know if it helps resolve your
        > problem.
        >
        > Best regards,
        >
        > Peter Huang
        > Microsoft Online Partner Support
        >
        > Get Secure! - www.microsoft.com/security
        > This posting is provided "AS IS" with no warranties, and confers no[/color]
        rights.[color=blue]
        >[/color]


        Comment

        • Brad

          #5
          Re: How to xml serialize arraylist of objects?

          Peter, a second followup if I may:
          The function below (somewhat similar to your button2_click) works fine,
          however with some traces I found instantiating the StringReader is quite
          expensive, ~1.7 seconds, for simple xml, also below. That was a bit
          disappointing as I expected to use this for extracting xml from multiple sql
          data rows but it will be to slow for an interactive web app.

          Brad

          =============== =============== ==============
          Public Function SelectedAttribu tes(ByVal attributes As String) As ArrayList
          Dim result As ArrayList
          If attributes.Leng th > 0 Then
          Dim mySerializer As System.Xml.Seri alization.XmlSe rializer _
          = New
          System.Xml.Seri alization.XmlSe rializer(GetTyp e(ArrayList) _
          , New Type() _

          {GetType(Catalo g.Item.Details. SelectedValue)} )

          ' This next line is what is costing a lot of time.
          Dim strReader As New StringReader(at tributes)

          Dim reader As New XmlTextReader(s trReader)
          result = CType(mySeriali zer.Deserialize (reader), ArrayList)
          Return result
          End If
          End Function

          =============== =============== ==============
          Xml that is the value of "attributes " and read by the stringreader

          <?xml version="1.0" encoding="utf-16"?>
          <ArrayOfAnyTy pe xmlns:xsd="http ://www.w3.org/2001/XMLSchema"
          xmlns:xsi="http ://www.w3.org/2001/XMLSchema-instance">
          <anyType xsi:type="Selec tedValue">
          <Attribute>Size </Attribute>
          <Value>L</Value>
          </anyType>
          <anyType xsi:type="Selec tedValue">
          <Attribute>Colo r</Attribute>
          <Value>Blue</Value>
          </anyType>
          </ArrayOfAnyType>



          "Peter Huang" <v-phuang@online.m icrosoft.com> wrote in message
          news:bC07akcAEH A.612@cpmsftngx a06.phx.gbl...[color=blue]
          > Hi Brad,
          >
          > Thanks for posting in the community.
          >
          > First of all, I would like to confirm my understanding of your issue.
          > From your description, I understand that you wants to serialize an
          > arraylist to a xml file and deserialize ti from the xml.
          > Have I fully understood you? If there is anything I misunderstood, please
          > feel free to let me know.
          >
          > Here I write the code sinippet.
          >
          > <code>
          > Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
          > System.EventArg s) Handles Button1.Click
          > Dim objs As New Group
          > Dim obj1 As New MyObject
          > obj1.Name = "Obj1Name"
          > Dim obj2 As New MyObject
          > obj2.Name = "Obj2Name"
          > objs.Info = New ArrayList
          > objs.Info.Add(o bj1)
          > objs.Info.Add(o bj2)
          > Dim x As XmlSerializer = New XmlSerializer(G etType(Group))
          > Dim writer As TextWriter = New StreamWriter("T est.xml")
          > x.Serialize(wri ter, objs)
          > writer.Close()
          > End Sub
          >
          > Private Sub Button2_Click(B yVal sender As System.Object, ByVal e As
          > System.EventArg s) Handles Button2.Click
          > Dim serializer As New XmlSerializer(G etType(Group))
          > ' A FileStream is needed to read the XML document.
          > Dim fs As New FileStream("Tes t.xml", FileMode.Open)
          > Dim reader As New XmlTextReader(f s)
          > Dim gp As Group = CType(serialize r.Deserialize(r eader), Group)
          > For Each o As MyObject In gp.Info
          > MsgBox(o.Name)
          > Next
          > End Sub
          >
          > Public Class Group
          > <XmlElement(Typ e:=GetType(MyOb ject))> _
          > Public Info As ArrayList
          > End Class
          > Public Class MyObject
          > Private _name As String
          > Public Property Name() As String
          > Get
          > Return _name
          > End Get
          > Set(ByVal Value As String)
          > _name = Value
          > End Set
          > End Property
          > End Class
          >
          > </code>
          >
          >
          > Also here is some links may help you.
          > Controlling XML Serialization Using Attributes
          > See section "Serializin g an ArrayList"
          >[/color]
          http://longhorn.msdn.microsoft.com/l...erializationby[color=blue]
          > xmlserializerwi thattributes.as px
          >
          > Examples of XML Serialization
          > See section: Serializing a Class that Implements the ICollection Interface
          >[/color]
          http://longhorn.msdn.microsoft.com/l...mlserializatio[color=blue]
          > nwithxmlseriali zer.aspx
          >
          > Please apply my suggestion above and let me know if it helps resolve your
          > problem.
          >
          > Best regards,
          >
          > Peter Huang
          > Microsoft Online Partner Support
          >
          > Get Secure! - www.microsoft.com/security
          > This posting is provided "AS IS" with no warranties, and confers no[/color]
          rights.[color=blue]
          >[/color]



          Comment

          • Peter Huang

            #6
            Re: How to xml serialize arraylist of objects?

            Hi Brad,

            Thanks for your quickly reply!

            Yes, the method below is also OK.
            New System.Xml.Seri alization.XmlSe rializer(GetTyp e(ArrayList), New
            Type() {GetType(MyObje ct)})

            But use a goup class will benifit more flexible.

            Also the stringreader seems to work fine on my side. Is the attributes
            somewhat huge in your side?[color=blue]
            > ' This next line is what is costing a lot of time.
            > Dim strReader As New StringReader(at tributes)[/color]

            Anyway have you tried to serialize the arraylist to an byte array and them
            store it into the database. Also when you want, you can deserialize the
            arraylist from the byte array, this may help you improve your performance.

            Dim sm As MemoryStream
            Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
            System.EventArg s) Handles Button1.Click
            Dim obj1 As New MyObject
            obj1.Name = "Obj1Name"
            Dim obj2 As New MyObject
            obj2.Name = "Obj2Name"
            Dim ar As New ArrayList
            ar.Add(obj1)
            ar.Add(obj2)

            Dim x As XmlSerializer = New
            System.Xml.Seri alization.XmlSe rializer(GetTyp e(ArrayList), New Type()
            {GetType(MyObje ct)})
            sm = New MemoryStream
            x.Serialize(sm, ar)
            'This will write the sm to byte array, and you can store into
            database.
            'sm.ToArray()
            End Sub

            Private Sub Button2_Click(B yVal sender As System.Object, ByVal e As
            System.EventArg s) Handles Button2.Click
            sm.Position = 0
            Dim serializer As XmlSerializer = New
            XmlSerializer(G etType(ArrayLis t), New Type() {GetType(MyObje ct)})
            'Here you can get the bytearray from the database and create a new memory
            stream.
            Dim reader As New XmlTextReader(s m)
            Dim gp As ArrayList = CType(serialize r.Deserialize(r eader),
            ArrayList)
            For Each o As MyObject In gp
            MsgBox(o.Name)
            Next
            sm.Close()
            End Sub


            Best regards,

            Peter Huang
            Microsoft Online Partner Support

            Get Secure! - www.microsoft.com/security
            This posting is provided "AS IS" with no warranties, and confers no rights.

            Comment

            Working...