Results 1 to 15 of 15

Thread: Serialize multiple objects into a single XML File

  1. #1
    Addicted Member
    Join Date
    Nov 10
    Posts
    152

    Serialize multiple objects into a single XML File

    I have a parent class with daughter and granddaughter classes. Now I want to XMLserialize all classes/objects in one code in order to generate, not one file for each object but, one file for all the objects. How do I do this? The posts I have read seem to have dead ends. I know how to serialize a single object but I need code to serialize all files at once into a single File. Good references are welcome. I use vb.net, but c# is also welcome. Thanks for assisting.

  2. #2
    PowerPoster techgnome's Avatar
    Join Date
    May 02
    Posts
    21,636

    Re: Serialize multiple objects into a single XML File

    if the daughter & grand daughter classes are members/properties of the parent class... and everything has been marked as serializable... then serializing the parent will serialize everything all the way down.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.-I also subscribe to all threads I participate, so there's no need to pm when there's an update.*
    *Proof positive that searching the forums does work: View Thread *
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *
    * Use Offensive Programming, not Defensive Programming. * On Error Resume Next is error ignoring, not error handling(tm).
    "There is a major problem with your code, and VB wants to tell you what it is.. but you have decided to put your fingers in your ears and shout 'I'm not listening!'" - si_the_geek on using OERN

  3. #3
    Addicted Member
    Join Date
    Nov 10
    Posts
    152

    Re: Serialize multiple objects into a single XML File

    When I serialize the parent class I get an empty file with the Root element only. The records are actually in the daughter classes, which are initialized on Window.Loaded. I tried to serialize the parent class as follows:

    Code:
     Dim pr  As  New parentClass
    Dim Xm As New XmlSerializer(pr.GetType)
    Dim tw As Textwriter = New StreamWriter(....filePath..)
    
    Xm.Serialize(tw,pr)          
    tw.Close
    How and where do I access the daughter objects here? I get lost on that question. I only get data if I reference one daughter object at a time as: Dim pr As New daughterClassO1 and do the rest as above. Then the whole daughter class referenced is serialized fine. Please help.

  4. #4
    PowerPoster techgnome's Avatar
    Join Date
    May 02
    Posts
    21,636

    Re: Serialize multiple objects into a single XML File

    you serialized an empty object.... OF COURSE you're going to get an empty file...

    You need to create your object, fill/populate it... then serialize it...

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.-I also subscribe to all threads I participate, so there's no need to pm when there's an update.*
    *Proof positive that searching the forums does work: View Thread *
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *
    * Use Offensive Programming, not Defensive Programming. * On Error Resume Next is error ignoring, not error handling(tm).
    "There is a major problem with your code, and VB wants to tell you what it is.. but you have decided to put your fingers in your ears and shout 'I'm not listening!'" - si_the_geek on using OERN

  5. #5
    Addicted Member
    Join Date
    Nov 10
    Posts
    152

    Re: Serialize multiple objects into a single XML File

    Would someone be kind enough to draft me an outline of how I can populate and serialize in a way that would generate the Xml file shown below: Take a look at the Class (shortened). Just do the header records. Thanks

    Code:
    Option Strict Off
    Option Explicit On
    
    Imports System.Xml.Serialization
    
    
    '''<remarks/>
    <System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432"),  _
     System.SerializableAttribute(),  _
     System.Diagnostics.DebuggerStepThroughAttribute(),  _
     System.ComponentModel.DesignerCategoryAttribute("code"),  _
     System.Xml.Serialization.XmlTypeAttribute(AnonymousType:=true),  _
     System.Xml.Serialization.XmlRootAttribute([Namespace]:="", IsNullable:=false)>  _
    Partial Public Class EducatorRegistration
        
        Private headerField As EducatorRegistrationHeader
        
        Private educatorInformationField() As EducatorRegistrationEducatorInformation
        
        Private trailerField As EducatorRegistrationTrailer
        
        '''<remarks/>
        Public Property Header() As EducatorRegistrationHeader
            Get
                Return Me.headerField
            End Get
            Set
                Me.headerField = value
            End Set
        End Property
        
        '''<remarks/>
        <System.Xml.Serialization.XmlElementAttribute("EducatorInformation")>  _
        Public Property EducatorInformation() As EducatorRegistrationEducatorInformation()
            Get
                Return Me.educatorInformationField
            End Get
            Set
                Me.educatorInformationField = value
            End Set
        End Property
        
        '''<remarks/>
        Public Property Trailer() As EducatorRegistrationTrailer
            Get
                Return Me.trailerField
            End Get
            Set
                Me.trailerField = value
            End Set
        End Property
    End Class
    
    '''<remarks/>
    <System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432"),  _
     System.SerializableAttribute(),  _
     System.Diagnostics.DebuggerStepThroughAttribute(),  _
     System.ComponentModel.DesignerCategoryAttribute("code"),  _
     System.Xml.Serialization.XmlTypeAttribute(AnonymousType:=true)>  _
    Partial Public Class EducatorRegistrationHeader
        
        Private recordField As EducatorRegistrationHeaderRecord
        
        '''<remarks/>
        Public Property Record() As EducatorRegistrationHeaderRecord
            Get
                Return Me.recordField
            End Get
            Set
                Me.recordField = value
            End Set
        End Property
    End Class
    
    '''<remarks/>
    <System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432"),  _
     System.SerializableAttribute(),  _
     System.Diagnostics.DebuggerStepThroughAttribute(),  _
     System.ComponentModel.DesignerCategoryAttribute("code"),  _
     System.Xml.Serialization.XmlTypeAttribute(AnonymousType:=true)>  _
    Partial Public Class EducatorRegistrationHeaderRecord
        
        Private filenameField As String
        
        Private provinceIDField As String
        
        Private emisNumberField As String
        
        Private statusIDField As String
        
        Private transactionCategoryIDField As String
        
        Private sequenceNumberField As String
        
        Private dateCreatedField As Date
        
        Private createdByField As String
        
        Private typeField As Byte
        
        '''<remarks/>
    
    
    ....................
    PROPERTY ACCESORS
    ..................
    
    
    End Class
    
    """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
      <?xml version="1.0" ?> 
    - <EducatorRegistration xmlns="urn:educatorreg-schema">
    - <Header>
    - <Record type="1">
      <Filename>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</Filename> 
      <ProvinceID>5</ProvinceID> 
      <EmisNumber>500000006</EmisNumber> 
      <StatusID>1</StatusID> 
      <TransactionCategoryID>13</TransactionCategoryID> 
      <SequenceNumber>1</SequenceNumber> 
      <DateCreated>2007-08-12</DateCreated> 
      <CreatedBy>aaaffffyyyyrtrr</CreatedBy> 
      </Record>
      </Header>
    - <EducatorInformation>
    - <EducatorBiographical>
    - <Record type="2">
      <ProvinceID>5</ProvinceID> 
      <EducatorNumber>XYZ507000001</EducatorNumber> 
      <EmisNumber>500000006</EmisNumber> 
      <TitleID>Mr</TitleID> 
      <EducatorFirstName>BBBB</EducatorFirstName> 
      <EducatorSecondName>BBBB</EducatorSecondName> 
      <EducatorSurname>AAAA</EducatorSurname> 
      <PersalNumber>CCCCC</PersalNumber> 
      <SACENumber>DDDDDD</SACENumber> 
      <GenderID>1</GenderID> 
      <PopulationGroupID>1</PopulationGroupID> 
      <BirthDate>20010212</BirthDate> 
      <EducatorTelephoneCode>021</EducatorTelephoneCode> 
      <EducatorTelephone>7881100</EducatorTelephone> 
      <EducatorCellphoneCode /> 
      <EducatorCellphone /> 
      <HomeLanguageID>2</HomeLanguageID> 
      <DisabilityStatusID>1</DisabilityStatusID> 
      <OtherDisability>Ahhhh</OtherDisability> 
      <DateRegistered>20070109</DateRegistered> 
      <PostLevelID>1</PostLevelID> 
      <YearsExperience /> 
      <ActualPositionID>1</ActualPositionID> 
      <ActingPositionID /> 
      <NatureAppointmentID>1</NatureAppointmentID> 
      <RemunerationID>1</RemunerationID> 
      <DurationID>1</DurationID> 
      <TeachingLevelID1>1</TeachingLevelID1> 
      <TeachingLevelID2 /> 
      <QualificationID /> 
      <REQVQualificationID>10</REQVQualificationID> 
      <LURITSEducatorID>0</LURITSEducatorID> 
      </Record>
      </EducatorBiographical>
    - <EducatorSubject>
    - <Record type="3">
      <EmisNumber>500000006</EmisNumber> 
      <EducatorNumber>508000001</EducatorNumber> 
      <Year>2007</Year> 
      <SubjectID>1</SubjectID> 
      <TeachingExperience>1</TeachingExperience> 
      <YearsFormalTraining>0</YearsFormalTraining> 
      <ExaminableID>1</ExaminableID> 
      </Record>
      </EducatorSubject>
    - <EducatorClass>
    - <Record type="4">
      <EmisNumber>500000006</EmisNumber> 
      <EducatorNumber>508000001</EducatorNumber> 
      <Year>2007</Year> 
      <SubjectID>1</SubjectID> 
      <GradeID>22</GradeID> 
      <Class>Penguins</Class> 
      <HoursPerWeek>03:30</HoursPerWeek> 
      <NumberLearners>10</NumberLearners> 
      </Record>
      </EducatorClass>
      </EducatorInformation>
    - <Trailer>
    - <Record type="9">
      <FileName /> 
      <NumberOfRecords>1</NumberOfRecords> 
      </Record>
      </Trailer>
      </EducatorRegistration>

  6. #6
    Addicted Member
    Join Date
    Nov 10
    Posts
    152

    Re: Serialize multiple objects into a single XML File

    I don't want to accept that this thread is too bit for all of us. There must be one or two brains that can crack this one. I personally have hit a brick wall. I just can't figure out how I can use the parent object to serialize data in the daughter objects. Please any help is welcome. Thanks.

  7. #7
    Code Monkey wild_bill's Avatar
    Join Date
    Mar 05
    Location
    Montana
    Posts
    2,817

    Re: Serialize multiple objects into a single XML File

    Try this
    Code:
        Sub Main()
    
            'get data from file
            Dim xmlData = IO.File.ReadAllText("C:\temp1\EducatorRegistration.xml")
            'create object from data
            Dim o = DeserializeFromString(xmlData)
    
        End Sub
    
        Private Function DeserializeFromString(ByVal input As String) As EducatorRegistration
    
            'Convert to byte array
            Dim encoding As New System.Text.UnicodeEncoding
            Dim bytes() As Byte = encoding.GetBytes(input)
    
            'read bytes into stream
            Dim ms As New System.IO.MemoryStream
            ms.Write(bytes, 0, bytes.Length)
            ms.Position = 0
    
            'get object from bytes
            Dim xs As New Xml.Serialization.XmlSerializer(GetType(EducatorRegistration))
            Return DirectCast(xs.Deserialize(ms), EducatorRegistration)
    
        End Function
    Attached Files Attached Files
    That is the very essence of human beings and our very unique capability to perform complex reasoning and actually use our perception to further our understanding of things. We like to solve problems. -Kleinma

    Does your code in post #46 look like my code in #45? No, it doesn't. Therefore, wrong is how it looks. - jmcilhinney

  8. #8
    New Member
    Join Date
    Feb 12
    Posts
    4

    Re: Serialize multiple objects into a single XML File

    This function receives a populated class, and a destination path. If the class is serializable, it doesn't care what kind it is. It converts the class to xml and saves it to the path you specify in the parm.


    Code:
        Public Shared Function SaveXMLObjectToFile(ByVal IncomingXMLObject As Object, ByVal Path As String) As Boolean
    
            Dim xmlString As String
            Dim WriteAFile As StreamWriter
            Dim filelocation As String
    
            Dim MemStream As New System.IO.MemoryStream
            Dim Ser As System.Xml.Serialization.XmlSerializer
            Dim encodingvalue As System.Text.Encoding = System.Text.UTF8Encoding.UTF8
            Dim writer As New System.Xml.XmlTextWriter(MemStream, encodingvalue)
    
            Dim Result As Boolean
    
            Try
                File.Delete(Path)
                Ser = New System.Xml.Serialization.XmlSerializer(IncomingXMLObject.GetType)
                Ser.Serialize(writer, IncomingXMLObject)
                MemStream = writer.BaseStream 'as system.io.memorystream
                xmlString = UTF8ByteArrayToString(MemStream.ToArray())   'Will Not Convert Byte Array from Diagram
                filelocation = Path
                WriteAFile = TheFileIn.AppendText(filelocation)
                WriteAFile.Write(xmlString)
                WriteAFile.Close()
                Result = True
            Catch e As Exception
                Result = False
            End Try
    
            Return Result
    
        End Function

  9. #9
    Addicted Member
    Join Date
    Nov 10
    Posts
    152

    Re: Serialize multiple objects into a single XML File

    Thanks guys. I will try this as soon as I get to my desk. If I don't come back, it would have worked. Thanks a lot.

  10. #10
    Code Monkey wild_bill's Avatar
    Join Date
    Mar 05
    Location
    Montana
    Posts
    2,817

    Re: Serialize multiple objects into a single XML File

    Please come back and mark the thread resolved using thread tools if the suggestions worked.
    That is the very essence of human beings and our very unique capability to perform complex reasoning and actually use our perception to further our understanding of things. We like to solve problems. -Kleinma

    Does your code in post #46 look like my code in #45? No, it doesn't. Therefore, wrong is how it looks. - jmcilhinney

  11. #11
    Addicted Member
    Join Date
    Nov 10
    Posts
    152

    Re: Serialize multiple objects into a single XML File

    Yes the function draws data from a populated class, Xmlserialize and save it. What still puzzles me though is do I pass just one object to the function or do I need to create and pass object for each of the five records classes? IF I pass one object, for which class? Like I said when I pass object for EducatorRegistration Class I get empty file. At last I had to process one record class at a time. Is this the best wAy to do it? I have also learnt that I needed to use DOM technology to build the XML document. My first time to learn and use this. Thanks a lot guys I have learnt at lot in the past few weeks,

  12. #12
    Code Monkey wild_bill's Avatar
    Join Date
    Mar 05
    Location
    Montana
    Posts
    2,817

    Re: Serialize multiple objects into a single XML File

    Using the class I provided, this works for me. I rewrote dmvprof's serialize method.
    Code:
        Sub Main()
    
            'get data from file
            Dim xmlData = IO.File.ReadAllText("C:\temp1\EducatorRegistration.xml")
            'create object from data
            Dim o = DeserializeFromString(xmlData)
    
            'save object to XML File
            SaveXMLObjectToFile(o, "C:\temp1\EducatorRegistration(2).xml")
        End Sub
    
        Private Function DeserializeFromString(ByVal input As String) As EducatorRegistration
    
            'Convert to byte array
            Dim encoding As New System.Text.UnicodeEncoding
            Dim bytes() As Byte = encoding.GetBytes(input)
    
            'read bytes into stream
            Dim ms As New System.IO.MemoryStream
            ms.Write(bytes, 0, bytes.Length)
            ms.Position = 0
    
            'get object from bytes
            Dim xs As New Xml.Serialization.XmlSerializer(GetType(EducatorRegistration))
            Return DirectCast(xs.Deserialize(ms), EducatorRegistration)
    
        End Function
    
        Public Sub SaveXMLObjectToFile(ByVal IncomingXMLObject As Object, ByVal Path As String)
    
            'Serialize object to a text file.
            Dim objStreamWriter As New IO.StreamWriter(Path)
            Dim x As New XmlSerializer(IncomingXMLObject.GetType)
            x.Serialize(objStreamWriter, IncomingXMLObject)
            objStreamWriter.Close()
    
        End Sub
    That is the very essence of human beings and our very unique capability to perform complex reasoning and actually use our perception to further our understanding of things. We like to solve problems. -Kleinma

    Does your code in post #46 look like my code in #45? No, it doesn't. Therefore, wrong is how it looks. - jmcilhinney

  13. #13
    New Member
    Join Date
    Feb 12
    Posts
    4

    Re: Serialize multiple objects into a single XML File

    I'm not sure I understand your question entirely. It sounds to me like haven't populated the Class properly prior to serializing it.

    I have a "UserToken" that I pass around in one of my apps. It has it's local fields as well as an array of the separate class "MenuOptions"

    Here is the definition for each of these classes.

    Code:
    Public Class UserToken
    
        Public UserName As String
        Public Supervisor As Boolean
        Public Division As String
        Public PersonID As Integer
        Public FullName As String
        Public MenuOptions As MenuOption()
    
    End Class
    
    Public Class MenuOption
    
        Public MenuCategory As String
        Public MenuOptionText As String
        Public OptionToExecute As String
        Public OnlineOnly As Boolean
        Public OptionEnabled As Boolean
    
    End Class

    To populate this class, I use the following method. (abbreviated)

    Code:
            If dr.HasRows Then
                        dr.Read()
                           With NewToken
                                .Division = dr("Division").ToString()
                                .Supervisor = dr("Supervisor")
                                .UserName = parmUserId
                                .PersonID = dr("PersonID")
                                .FullName = dr("FullName")
                             End With
    
                             dr.Close()
    
                             NewToken.MenuOptions = AuthorizeUser(parmUserId)
    
                      End If
    My array of MenuOptions has to be populated elsewhere. I have to create a New instance of it, populate it, and then set the Array of MenuOptions defined in my UserToken Class equal to the one I just created.

    I do this above with the line

    NewToken.MenuOptions = AuthorizeUser(parmUserId)


    Code:
        Private Function AuthorizeUser(ByRef UserName As String) As MenuOption()
    
            Dim MenuOptions As List(Of MenuOption)
    
            sb.Append("SELECT c.[CategoryName], o.[OptionText], o.[OptionToExecute], o.[OnlineOnly], o.[OptionEnabled] ")
            sb.Append(" FROM [VAPDLIB].[Police].[menuUserGroups] g,")
            
            <SNIP>
    
            DR = sqlCommand.ExecuteReader
    
            Do While (DR.Read())
                MenuOptions.Add(GetMenuOption(DR))
            Loop
    
            DR.Close()
    
    
            Return MenuOptions.ToArray()
    
        End Function
    
        Private Function GetMenuOption(ByVal dr As SqlDataReader) As MenuOption
    
            Dim NewOption As New MenuOption
    
            With NewOption
                .MenuCategory = dr("CategoryName").ToString()
                .MenuOptionText = dr("OptionText").ToString()
                .OptionToExecute = dr("OptionToExecute").ToString()
                .OnlineOnly = dr("OnlineOnly")
                .OptionEnabled = dr("OptionEnabled")
            End With
    
            Return NewOption
    
        End Function


    Once you have your class populated properly, serializing it is a breeze.

    To serialize both the "UserToken" and it's "MenuOptions", I just use the "UserToken" object that contains the "MenuOptions".
    Last edited by dmvprof; Aug 20th, 2012 at 11:19 AM.

  14. #14
    PowerPoster techgnome's Avatar
    Join Date
    May 02
    Posts
    21,636

    Re: Serialize multiple objects into a single XML File

    It sounds to me like haven't populated the Class properly prior to serializing it.
    That's what I thought too...

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.-I also subscribe to all threads I participate, so there's no need to pm when there's an update.*
    *Proof positive that searching the forums does work: View Thread *
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *
    * Use Offensive Programming, not Defensive Programming. * On Error Resume Next is error ignoring, not error handling(tm).
    "There is a major problem with your code, and VB wants to tell you what it is.. but you have decided to put your fingers in your ears and shout 'I'm not listening!'" - si_the_geek on using OERN

  15. #15
    Addicted Member
    Join Date
    Nov 10
    Posts
    152

    Re: Serialize multiple objects into a single XML File

    I know I have taken a bit longer to finalize this thread. Its because I needed to do some background reading in order to master what is going on here. I want to thank you especially dmvprof and techgnome for their help. Dmvprof gave me a breakthrough although it took me some addiitional reading to grasp his solution. Thanks a lot. Problem solved!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •