Spiral Sites Spiral Sites - 6 months ago 22
Vb.net Question

duplicated element in xml where vb class has a list of property when exporting as serialize to xml

I have a class defined as below:

Public Class details
Public Property description As String
Public Property rooms As New List(Of rooms)
End Class

Public Class rooms
Public Property room_name As String
Public Property room_description As String
End Class


Its house details that has multiple rooms per house.

I am coding it as follows:

Dim clsPDts As New details
clsPDts.description = "test property name"
Dim tmpRoom As New rooms
tmpRoom.room_name = "BEDROOM ONE"
tmpRoom.room_description = "Fitted wardrobes with mirror sliding doors"
clsPDts.details.rooms.Add(tmpRoom)


Then outputting as follows:

Dim objStreamWriter As New StreamWriter("D:\Product.xml")
Dim x As New XmlSerializer(clsPDts.GetType)
x.Serialize(objStreamWriter, clsPDts)
objStreamWriter.Close()


The XML file should be as below as that's the format it MUST BE:

<details>
<description>A Two Bedroomed Second Floor Apartment Situated Within this Seafront Development.</description>
<rooms>
<room_name>COMMUNAL HALLWAY</room_name>
<room_description>Communal entrance door with entry phone system.</room_description>
</rooms>
<rooms>
<room_name>ENTRANCE HALL</room_name>
<room_description>Personal entrance door. Built-in airing cupboard, storage heater.</room_description>
</rooms>
<rooms>
<room_name>BEDROOM ONE</room_name>
<room_description>Fitted wardrobes with mirror fronted sliding doors</room_description>
</rooms>
</details>


But its currently coming out as below with the extra room element around the other multiple rooms:

<details>
<description>A Two Bedroomed Second Floor Apartment Situated Within this Seafront Development.</description>
<rooms>
<rooms>
<room_name>COMMUNAL HALLWAY</room_name>
<room_description>Communal entrance door with entry phone system.</room_description>
</rooms>
<rooms>
<room_name>ENTRANCE HALL</room_name>
<room_description>Personal entrance door. Built-in airing cupboard, storage heater.</room_description>
</rooms>
<rooms>
<room_name>BEDROOM ONE</room_name>
<room_description>Fitted wardrobes with mirror fronted sliding doors</room_description>
</rooms>
</rooms>
</details>


I am unsure how i can get rid of the extra outer element?

Answer

You need to specify the Tag as XmlElement like in the code below

Imports System.Xml
Imports System.Xml.Serialization
Module Module1

    Sub Main()

    End Sub

End Module

<XmlRoot("details")>
Public Class details
    <XmlElement("description")>
    Public Property description As String
    <XmlElement("rooms")>
    Public Property rooms As New List(Of rooms)
End Class

<XmlRoot("rooms")>
Public Class rooms
    <XmlElement("room_name")>
    Public Property room_name As String
    <XmlElement("room_decription")>
    Public Property room_description As String
End Class