Search code examples
xmlvb.netclassmodels

Converting model class to XML


I have the next classes in vb.net:

Class A 
    Public Property Bs As New List(Of B)
End Class

Class B
    Public Property D As String
    Public Property E As String
End class

I wish to convert them in xml using next code:

Dim sw1 = New StringWriter()
Dim xs1 As New XmlSerializer(A.GetType)
xs1.Serialize(New XmlTextWriter(sw1), A)
xml = xml.Replace("{1}", sw1.ToString())

The format of that classes will be:

<A>
  <Bs>
    <B>
      <D>1</D>
      <E>2</E>
    </B>
    <B>
      <D>3</D>
      <E>2</E>
    </B>
</Bs>
</A>

But I would wish to have next one:

<A>
    <B>
      <D>1</D>
      <E>2</E>
    </B>
    <B>
      <D>3</D>
      <E>2</E>
    </B>
</A>

Without tag Bs, how can I do it using XmlElement or XArray... in the class?


Solution

  • You should be able to achieve this behaviour by applying the XmlElement attribute to your list, ignoring XmlArray and XmlArrayItem:

    Class A
        <XmlElement("B")> _
        Public Property Bs As New List(Of B)
    End Class