locked
Use XML as tiny database of objects RRS feed

  • Question

  • Hi,

    I have an object which I already serialize and save it to an XML file using the following code. Now, I need to open the XML and be able to

    • Add another object of the same type
    • Delete an object of the list based on a value (Name)

    Any help will be appreciated !

    Public Class Person
        Public Name As String
        Public Age As byte
    End Class
    
    Private Sub ProcessObject()
    
            Dim File As String = "C:\Temp\TransPnd.xml"
            Dim xml As New XmlDocument
    
            If IO.File.Exists(File) Then
    
                xml.Load(File)
                'HERE is where I need to add or delete another Person
    
            Else
    
                Dim tp As New TransPending
                Dim ser As XmlSerializer
                Dim stw As New StringWriter()
    
                With tp
                    .Name= "John"
                    .Age= 25
                End With
    
                ser = New XmlSerializer(GetType(TransPending))
                ser.Serialize(stw, tp)
    
                xml.LoadXml(stw.ToString)
                xml.Save(File)
    
            End If
    
        End Sub


    G.Waters

    Sunday, December 2, 2018 8:01 PM

Answers

  • The following can be used to serialize and desalinize collections.  Which is what I  think you want to do.

    First we have a module with methods to serialize and desalinize the collections.  You want to use a collection as this will allow you to add/change and remove items from the collection.  At the end or whenever you want you can serialize the new data back to the .xml file.

    Methods in module:

    Imports System.IO
    Imports System.Xml.Serialization
    Imports System.Runtime.Serialization.Formatters.Binary
    Imports System.Runtime.Serialization
    
    Public Class SerializerHelper
    	Public Shared Sub SaveToFile(ByVal fileName As String, ByVal p As Object, types As Type())
    		'Serialize object to a text file.
    		Dim objStreamWriter As New StreamWriter(fileName)
    		Dim x As New XmlSerializer(p.GetType, types)
    		x.Serialize(objStreamWriter, p)
    		objStreamWriter.Close()
    	End Sub
    
    	Public Shared Function GetFromFile(ByVal fileName As String, ByRef p As Object, types As Type()) As Object
            'Deserialize text file to a new object.
            Dim direct As String = Directory.GetCurrentDirectory()
            Dim fn As String = Path.Combine(direct, fileName)
            If Not File.Exists(fn) Then
                Dim stp As Integer = 1
                Return Nothing
            End If
            Dim x As New XmlSerializer(p.GetType, types)
    		Dim objStreamReader As New StreamReader(fileName)
    		Dim p2 As Object
    		p2 = x.Deserialize(objStreamReader)
    		objStreamReader.Close()
    		Return p2
    	End Function
    
    	Public Shared Function GetFromResource(ByVal resource As Stream, ByRef p As Object) As Object
    		'Deserialize text file to a new object.
    		Dim x As New XmlSerializer(p.GetType)
    		Dim objStreamReader As New StreamReader(resource)
    		Dim p2 As Object
    		p2 = x.Deserialize(objStreamReader)
    		objStreamReader.Close()
    		Return p2
    	End Function
    End Class

    Now to use this I have a collection of transactions.  This will require you to create an object to hold your data.

        Private _Transactions As New ObservableCollection(Of Transaction)
        Public Property Transactions() As ObservableCollection(Of Transaction)
            Get
                Return _Transactions
            End Get
            Set(ByVal value As ObservableCollection(Of Transaction))
                _Transactions = value
                RaiseChanged("Transactions")
            End Set
        End Property
    

    Then to read the xml file into the collection you would do the following:

            Dim retVal = SerializerHelper.GetFromFile(CurrentFileName, Transactions, Nothing)
    

    and to write the modified data back to the xml file you would do:

            SerializerHelper.SaveToFile(curFileName, Transactions, Nothing)
    

    Hope this helps.

      

    Lloyd Sheen

    • Marked as answer by George Waters Monday, December 3, 2018 8:25 AM
    Sunday, December 2, 2018 9:26 PM

All replies

  • The following can be used to serialize and desalinize collections.  Which is what I  think you want to do.

    First we have a module with methods to serialize and desalinize the collections.  You want to use a collection as this will allow you to add/change and remove items from the collection.  At the end or whenever you want you can serialize the new data back to the .xml file.

    Methods in module:

    Imports System.IO
    Imports System.Xml.Serialization
    Imports System.Runtime.Serialization.Formatters.Binary
    Imports System.Runtime.Serialization
    
    Public Class SerializerHelper
    	Public Shared Sub SaveToFile(ByVal fileName As String, ByVal p As Object, types As Type())
    		'Serialize object to a text file.
    		Dim objStreamWriter As New StreamWriter(fileName)
    		Dim x As New XmlSerializer(p.GetType, types)
    		x.Serialize(objStreamWriter, p)
    		objStreamWriter.Close()
    	End Sub
    
    	Public Shared Function GetFromFile(ByVal fileName As String, ByRef p As Object, types As Type()) As Object
            'Deserialize text file to a new object.
            Dim direct As String = Directory.GetCurrentDirectory()
            Dim fn As String = Path.Combine(direct, fileName)
            If Not File.Exists(fn) Then
                Dim stp As Integer = 1
                Return Nothing
            End If
            Dim x As New XmlSerializer(p.GetType, types)
    		Dim objStreamReader As New StreamReader(fileName)
    		Dim p2 As Object
    		p2 = x.Deserialize(objStreamReader)
    		objStreamReader.Close()
    		Return p2
    	End Function
    
    	Public Shared Function GetFromResource(ByVal resource As Stream, ByRef p As Object) As Object
    		'Deserialize text file to a new object.
    		Dim x As New XmlSerializer(p.GetType)
    		Dim objStreamReader As New StreamReader(resource)
    		Dim p2 As Object
    		p2 = x.Deserialize(objStreamReader)
    		objStreamReader.Close()
    		Return p2
    	End Function
    End Class

    Now to use this I have a collection of transactions.  This will require you to create an object to hold your data.

        Private _Transactions As New ObservableCollection(Of Transaction)
        Public Property Transactions() As ObservableCollection(Of Transaction)
            Get
                Return _Transactions
            End Get
            Set(ByVal value As ObservableCollection(Of Transaction))
                _Transactions = value
                RaiseChanged("Transactions")
            End Set
        End Property
    

    Then to read the xml file into the collection you would do the following:

            Dim retVal = SerializerHelper.GetFromFile(CurrentFileName, Transactions, Nothing)
    

    and to write the modified data back to the xml file you would do:

            SerializerHelper.SaveToFile(curFileName, Transactions, Nothing)
    

    Hope this helps.

      

    Lloyd Sheen

    • Marked as answer by George Waters Monday, December 3, 2018 8:25 AM
    Sunday, December 2, 2018 9:26 PM
  • Hi,

    see the code,you can use linq to create, add, delete XML documents.

    Imports System.IO
    Imports System.Xml
    Imports System.Xml.Serialization
    
    Public Class Form1
    
        Dim File As String = "D:\TransPnd.xml"
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim xdoc As XDocument = New XDocument()
            Dim root As XElement = New XElement("school")
            Dim cls As XElement = New XElement("class")
            Dim stu1 As XElement = New XElement("student")
            stu1.SetElementValue("Name", "Alex")
            stu1.SetElementValue("Age", "24")
            Dim stu2 As XElement = New XElement("student")
            stu2.SetElementValue("Name", "John")
            stu2.SetElementValue("Age", "18")
            cls.Add(stu1)
            cls.Add(stu2)
            root.Add(cls)
            xdoc.Add(root)
            xdoc.Save(File)
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim xdoc As XDocument = XDocument.Load(File)
            Dim xeleRoot As XElement = xdoc.Root
            Dim xeleClass As XElement = xeleRoot.Element("class")
            Dim xeleStu3 As XElement = New XElement("student")
            xeleStu3.SetElementValue("Name", "Zack")
            xeleStu3.SetElementValue("Age", "40")
            xeleClass.Add(xeleStu3)
            xdoc.Save(File)
        End Sub
    
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            Dim xdoc As XDocument = XDocument.Load(File)
            Dim xeleRoot As XElement = xdoc.Root
            Dim xeleClass As XElement = xeleRoot.Elements("class").Elements("student").Where(Function(x) x.Element("Name").Value = "Alex").Single()
            xeleClass.Remove()
            xdoc.Save(File)
        End Sub
    End Class
    

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, December 3, 2018 8:12 AM
  • Thanks pal !!!

    G.Waters

    Monday, December 3, 2018 8:25 AM