通用XML反序列化器,其中xml在元素中具有属性

时间:2019-02-01 12:21:59

标签: xml vb.net api deserialization xml-deserialization

我正在使用VB.Net

我有像这样的通用XML反序列化器方法

Public Function Deserialize(xml As String) As T
        Dim result As T = Nothing

        If Not String.IsNullOrEmpty(xml) Then
            Dim tr As IO.TextReader = New IO.StringReader(xml)
            Dim reader As XmlReader = XmlReader.Create(tr)
            Dim serializer As XmlSerializer = New XmlSerializer(GetType(T))
            If serializer.CanDeserialize(reader) Then
                result = CType(serializer.Deserialize(reader), T)
            End If
        End If

        Return result
    End Function

我想反序列化以下XML

  <?xml version='1.0' encoding='UTF-8' standalone='yes'?>
    <apiResponse version="1.0">
    <areaOfControlResponse>
    <aocs>
    <aoc id="5840" name="ABE" address="BS16 2PX, United Kingdom"/>
    <aoc id="7626" name="MAIN" address="Willow Bed Close 45, BS16 XXX, United Kingdom"/>
    <aoc id="7629" name="test" address="X Road, BS16, United Kingdom"/>
    </aocs>
    </areaOfControlResponse>
    </apiResponse>

我已经创建了这样的对象

Imports System.Xml.Serialization
Namespace AreaOfControlResponseClasses
    <XmlType(TypeName:="apiResponse")>
    Public Class AreaOfControlApiResponse
        <XmlArray("areaOfControlResponse")>
        Public Property AreaOfControlResponse As List(Of AOCS)
    End Class

    <XmlType(TypeName:="aocs")>
    Public Class AOCS
        <XmlArray("aoc")>
        Public Property AreaOfControl As List(Of AOC)
    End Class

    Public Class AOC

        '<XmlElement("aoc")>
        'Public Property Aoc As String

        <XmlAttribute("id")>
        Public Property AOCID As String

        <XmlAttribute("name")>
        Public Property AOCName As String

        <XmlAttribute("address")>
        Public Property AOCAddress As String
    End Class

End Namespace

当我反序列化时,我可以看到一个AreaOfcontrolResponse,并且其中有一个空白的AreaOfControl。我认为我的对象定义不正确,因此反序列化失败。有人可以指出我正确的方向吗?

0 个答案:

没有答案