xml 中的重复元素,其中 vb class 在导出为序列化到 xml 时有一个 属性 的列表

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

我有一个 class 定义如下:

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

它的房子详细信息,每间房子有多个房间。

我编码如下:

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)

然后输出如下:

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

XML 文件应该如下所示,因为它必须是这样的格式:

<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>  

但它目前如下所示,其他多个房间周围有额外的房间元素:

<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>

我不确定如何去掉多余的外部元素?

您需要像下面的代码一样将标签指定为 XmlElement

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