locked
How to serialize class objects to XML RRS feed

  • Question

  • Hi,

    I have a class customers and i would like to export my class to xml. I tried following  and i get XmlSerializer is not defined error.

    code to serialize.

            ' Create the serializer
            Dim serializer As New XmlSerializer(GetType(Customers))
    
            ' Serialize the object to an XML file
            Using streamWriter As StreamWriter = File.CreateText("CustomerXML.xml")
                serializer.Serialize(streamWriter, customerList)
            End Using


    Imports System.Xml.Serialization
    Public Class CustomerManager
    
        Public Shared Function GetAllCustomers() As Customers
    
            Dim customerList As New Customers()
            customerList.Add(New Customer("BOTTM", "Bottom-Dollar Markets", "Tsawassen", "BC", "Canada"))
            customerList(0).Orders.Add(New Order(1, "BOTTM", #1/4/2004#, #1/11/2004#))
            customerList(0).Orders.Add(New Order(2, "BOTTM", #2/9/2004#, #2/16/2004#))
            customerList(0).Orders.Add(New Order(3, "BOTTM", #3/2/2004#, #3/7/2004#))
            customerList(0).Orders(0).subOrders.Add(New SubOrder(1, "Test", "T.01"))
    
            customerList.Add(New Customer("GOURL", "Gourmet Lanchonetes", "Campinas", "SP", "Brazil"))
            customerList(1).Orders.Add(New Order(4, "GOURL", #4/7/2004#, #4/14/2004#))
            customerList(1).Orders.Add(New Order(5, "GOURL", #5/1/2004#, #5/14/2004#))
            customerList(1).Orders.Add(New Order(6, "GOURL", #6/20/2004#, #6/23/2004#))
            customerList(1).Orders(0).subOrders.Add(New SubOrder(4, "Test1", "t.01"))
            customerList(1).Orders(1).subOrders.Add(New SubOrder(5, "Test5", "t.015"))
    
    
            customerList.Add(New Customer("GREAL", "Great Lakes Food Market", "Eugene", "OR", "USA"))
            customerList(2).Orders.Add(New Order(7, "GREAL", #7/7/2004#, #7/14/2004#))
            customerList(2).Orders.Add(New Order(8, "GREAL", #8/1/2004#, #8/14/2004#))
            customerList(2).Orders.Add(New Order(9, "GREAL", #9/20/2004#, #9/23/2004#))
            customerList(2).Orders(0).subOrders.Add(New SubOrder(7, "Test7", "T.015"))
    
            Return customerList
        End Function
    
        Public Shared Function GetNewCustomer() As Customer
            Return New Customer("CustID", "CompanyName", "City", "Region", "Country")
        End Function
    End Class
    Imports System.Xml.Serialization
    <Serializable()>
    Public Class Customer
    
        Public Sub New(ByVal customerId As String, ByVal companyName As String, ByVal city As String, ByVal region As String, ByVal country As String)
            Initialize()
            customerIDValue = customerId
            companyNameValue = companyName
            cityValue = city
            regionValue = region
            countryValue = country
        End Sub
    
        Private Sub Initialize()
            ordersValue = New Orders()
        End Sub
    
        Private customerIDValue As String
        ''' <summary>
        ''' Identifier for the customer
        ''' </summary>
        Public Property CustomerID() As String
            Get
                Return customerIDValue
            End Get
            Set(ByVal value As String)
                customerIDValue = value
            End Set
        End Property
    
        Private companyNameValue As String
        ''' <summary>
        ''' The name of this customer
        ''' </summary>
        Public Property CompanyName() As String
            Get
                Return companyNameValue
            End Get
            Set(ByVal Value As String)
                companyNameValue = Value
            End Set
        End Property
    
    
        Private cityValue As String
        ''' <summary>
        ''' The city where this customer is located
        ''' </summary>
        Public Property City() As String
            Get
                Return cityValue
            End Get
            Set(ByVal Value As String)
                cityValue = Value
            End Set
        End Property
    
        Private regionValue As String
        ''' <summary>
        ''' The region where this customer is located
        ''' </summary>
        Public Property Region() As String
            Get
                Return regionValue
            End Get
            Set(ByVal Value As String)
                regionValue = Value
            End Set
        End Property
    
        Private countryValue As String
        ''' <summary>
        ''' The country where this customer is located
        ''' </summary>
        Public Property Country() As String
            Get
                Return countryValue
            End Get
            Set(ByVal Value As String)
                countryValue = Value
            End Set
        End Property
    
        Private WithEvents ordersValue As Orders
        ''' <summary>
        ''' The orders for this customer
        ''' </summary>
        Public Property Orders() As Orders
            Get
                Return ordersValue
            End Get
            Set(ByVal value As Orders)
                ordersValue = value
            End Set
        End Property
    
        Private Sub ordersValue_AddingNew(ByVal sender As Object, ByVal e As System.ComponentModel.AddingNewEventArgs) Handles ordersValue.AddingNew
            e.NewObject = New Order(999, Me.CustomerID, Date.Today, DateAdd(DateInterval.Day, 30, Date.Today))
        End Sub
    End Class
    
    Public Class Customers
        Inherits System.ComponentModel.BindingList(Of Customer)
    End Class

    thanks

    Monday, September 28, 2020 9:19 AM

Answers

  • It seems it will not serialize classes which has a constructor with parameters so i solved it by removing parameters for the constructors. 

     
    • Marked as answer by Shan1986 Friday, October 2, 2020 1:45 PM
    Friday, October 2, 2020 1:45 PM

All replies

  • Make sure that your project includes a reference to System.Xml. (See Solution Explorer or Project Properties). Add ‘Imports System.Xml.Serialization’ line to your file.

    Monday, September 28, 2020 1:22 PM
  • An alternative which allows things like in this case to provide different values and totals. I used Entity Framework so I did not have to mock up data.

    Note I have the customer name as an attribute and as a element to show it's possible to have options. 

    Dim xmlData As XElement
    
    Using context As New NorthWindContext
        xmlData =
            <orders>
                <%= From customer In context.Customers.ToList()
                    Select
                            <customer id=<%= customer.CustomerIdentifier %> CustomerName=<%= customer.CompanyName %>>
                                <Name><%= customer.Contact.FullName %></Name>
                                <Address><%= customer.Street %></Address>
                                <City><%= customer.City %></City>
                                <Zip><%= customer.PostalCode %></Zip>
                                <orders>
                                    <%= From order In customer.Orders
                                        Select
                                        <Order total=<%= Aggregate Detail In order.OrderDetails
                                            Into Sum(Detail.UnitPrice * Detail.Quantity) %>>
                                            <Date><%= order.OrderDate %></Date>
                                            <Details>
                                                <%= From detail In order.OrderDetails
                                                    Select
                                                    <Product id=<%= detail.ProductID %>>
                                                        <Name>
                                                            <%= detail.Product.ProductName %>
                                                        </Name>
                                                    </Product> %>
                                            </Details>
                                        </Order> %>
                                </orders>
                            </customer> %>
            </orders>
    
        xmlData.Save("All.xml")
    
    End Using

    Each Customer comes up as follows

    <customer id="3" CustomerName="Antonio Moreno Taquería">
    <Name>Antonio Moreno</Name>
    <Address>Mataderos  2312</Address>
    <City>México D.F.</City>
    <Zip>05023</Zip>
    <orders>
      <Order total="403.2000">
    	<Date>2014-11-27T00:00:00</Date>
    	<Details>
    	  <Product id="11">
    		<Name>Queso Cabrales</Name>
    	  </Product>
    	</Details>
      </Order>
      <Order total="881.2500">
    	<Date>2015-04-15T00:00:00</Date>
    	<Details>
    	  <Product id="43">
    		<Name>Ipoh Coffee</Name>
    	  </Product>
    	  <Product id="48">
    		<Name>Chocolade</Name>
    	  </Product>
    	</Details>
      </Order>
      <Order total="2156.5000">
    	<Date>2015-05-13T00:00:00</Date>
    	<Details>
    	  <Product id="11">
    		<Name>Queso Cabrales</Name>
    	  </Product>
    	  <Product id="40">
    		<Name>Boston Crab Meat</Name>
    	  </Product>
    	  <Product id="57">
    		<Name>Ravioli Angelo</Name>
    	  </Product>
    	  <Product id="59">
    		<Name>Raclette Courdavault</Name>
    	  </Product>
    	</Details>
      </Order>
      <Order total="2082.0000">
    	<Date>2015-06-19T00:00:00</Date>
    	<Details>
    	  <Product id="17">
    		<Name>Alice Mutton</Name>
    	  </Product>
    	  <Product id="34">
    		<Name>Sasquatch Ale</Name>
    	  </Product>
    	  <Product id="53">
    		<Name>Perth Pasties</Name>
    	  </Product>
    	</Details>
      </Order>
      <Order total="956.9000">
    	<Date>2015-09-22T00:00:00</Date>
    	<Details>
    	  <Product id="26">
    		<Name>Gumbär Gummibärchen</Name>
    	  </Product>
    	  <Product id="33">
    		<Name>Geitost</Name>
    	  </Product>
    	</Details>
      </Order>
      <Order total="375.5000">
    	<Date>2015-09-25T00:00:00</Date>
    	<Details>
    	  <Product id="33">
    		<Name>Geitost</Name>
    	  </Product>
    	  <Product id="66">
    		<Name>Louisiana Hot Spiced Okra</Name>
    	  </Product>
    	  <Product id="75">
    		<Name>Rhönbräu Klosterbier</Name>
    	  </Product>
    	</Details>
      </Order>
      <Order total="660.0000">
    	<Date>2016-01-28T00:00:00</Date>
    	<Details>
    	  <Product id="2">
    		<Name>Chang</Name>
    	  </Product>
    	  <Product id="42">
    		<Name>Singaporean Hokkien Fried Mee</Name>
    	  </Product>
    	</Details>
      </Order>
    </orders>
    </customer>


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange


    Monday, September 28, 2020 1:36 PM
  • Make sure that your project includes a reference to System.Xml. (See Solution Explorer or Project Properties). Add ‘Imports System.Xml.Serialization’ line to your file.

    Hallo Viorel, I do have "Imports System.Xml.Serialization " in my file as you can see. Still it shows XmlSerializer is not defined. Any idea Why?

    Thanks

    Monday, September 28, 2020 7:26 PM
  • Make sure that your project includes a reference to System.Xml. (See Solution Explorer or Project Properties). Add ‘Imports System.Xml.Serialization’ line to your file.

    Hallo Viorel, I do have "Imports System.Xml.Serialization " in my file as you can see. Still it shows XmlSerializer is not defined. Any idea Why?

    Thanks

    Make sure that your project includes a reference to System.Xml. (See Solution Explorer or Project Properties). 

    Monday, September 28, 2020 7:34 PM
  • Make sure that your project includes a reference to System.Xml. (See Solution Explorer or Project Properties). Add ‘Imports System.Xml.Serialization’ line to your file.

    Hallo Viorel, I do have "Imports System.Xml.Serialization " in my file as you can see. Still it shows XmlSerializer is not defined. Any idea Why?

    Thanks

    Make sure that your project includes a reference to System.Xml. (See Solution Explorer or Project Properties). 

    Thanks Viorel. Now it does not show this error. 
    Monday, September 28, 2020 7:44 PM
  • Hi Shan1986,

    >>Now it does not show this error.

    Did you solve your problem? If your question has been answered then please click the "Mark as Answer" Link at the bottom of the correct post(s), so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Xingyu Zhao


    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.

    Tuesday, September 29, 2020 8:37 AM
  • My problem is not solved. i am getting this error "value cannot be null" any idea.

    i am trying to serialize in this one.

    Imports System.Xml.Serialization
    <XmlRoot("Customer")>
    Public Class Customer
    
        Public Sub New(ByVal customerId As String, ByVal companyName As String, ByVal city As String, ByVal region As String, ByVal country As String)
            Initialize()
            customerIDValue = customerId
            companyNameValue = companyName
            cityValue = city
            regionValue = region
            countryValue = country
        End Sub
    
        Private Sub Initialize()
            ordersValue = New Orders()
        End Sub
    
        Private customerIDValue As String
        <XmlElement("customerIDValue")>
        Public Property CustomerID() As String
            Get
                Return customerIDValue
            End Get
            Set(ByVal value As String)
                customerIDValue = value
            End Set
        End Property
    
        Private companyNameValue As String
        <XmlElement("CompanyName")>
        Public Property CompanyName() As String
            Get
                Return companyNameValue
            End Get
            Set(ByVal Value As String)
                companyNameValue = Value
            End Set
        End Property
    
    
        Private cityValue As String
        <XmlElement("cityValue")>
        Public Property City() As String
            Get
                Return cityValue
            End Get
            Set(ByVal Value As String)
                cityValue = Value
            End Set
        End Property
    
        Private regionValue As String
        <XmlElement("regionValue")>
        Public Property Region() As String
            Get
                Return regionValue
            End Get
            Set(ByVal Value As String)
                regionValue = Value
            End Set
        End Property
    
        Private countryValue As String
        <XmlElement("countryValue")>
        Public Property Country() As String
            Get
                Return countryValue
            End Get
            Set(ByVal Value As String)
                countryValue = Value
            End Set
        End Property
    
        Private WithEvents ordersValue As Orders
        Public Property Orders() As Orders
            Get
                Return ordersValue
            End Get
            Set(ByVal value As Orders)
                ordersValue = value
            End Set
        End Property
    
        Public ReadOnly Property FullName() As String
            Get
                Return $"{Country} {City}"
            End Get
        End Property
    
    
        Private Sub ordersValue_AddingNew(ByVal sender As Object, ByVal e As System.ComponentModel.AddingNewEventArgs) Handles ordersValue.AddingNew
            e.NewObject = New Order(999, Me.CustomerID, Date.Today, DateAdd(DateInterval.Day, 30, Date.Today))
        End Sub
    End Class
    
    Public Class Customers
        Inherits System.ComponentModel.BindingList(Of Customer)
    End Class

    • Edited by Shan1986 Wednesday, September 30, 2020 4:27 PM
    Wednesday, September 30, 2020 4:25 PM
  • Hi Shan1986,

    Thanks for your feedback.

    It seems that you want to serialize a list of 'Customer' objects.

    Here's a related reference you can refer to.

    XML Serialize generic list of serializable objects

    The code in the reference is c#, and you can convert them to vb.net.

    Besides, if I have any misunderstanding, please provide more details about 'Order' and 'Orders'.

    Best Regards,

    Xingyu Zhao


    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.

    Thursday, October 1, 2020 5:44 AM
  • It seems it will not serialize classes which has a constructor with parameters so i solved it by removing parameters for the constructors. 

     
    • Marked as answer by Shan1986 Friday, October 2, 2020 1:45 PM
    Friday, October 2, 2020 1:45 PM