xml中的重复元素,其中vb类在作为serialize导出到xml时具有属性列表

时间:2016-06-06 20:38:58

标签: xml vb.net class serialization xml-serialization

我的课程定义如下:

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>

我不确定如何摆脱额外的外部因素?

1 个答案:

答案 0 :(得分:0)

您需要将标记指定为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