Vb.Net Xml将xml属性分解为类对象

时间:2013-03-26 14:39:06

标签: xml vb.net serialization deserialization

我无法将xml属性反序列化为类属性。

<?xml version="1.0" encoding="UTF-8" ?> 
<Ball clientid="xyz">
    <Name>Tommy</Name>
    <ballColor transactionid="1234">White</ballColor>
    <radius>9</radius>
    <PowerLevel>9001</PowerLevel>
    <RandomProp>This is another property</RandomProp>
</Ball>

我正在使用的XML ...现在我将发布我的代码。问题是我能够将clientid带入属性,但不是'transactionid'所以我无法提取子元素的属性

Imports System.Xml.Serialization
Public Class Ball
    Inherits ballColor
    Public Property Name As String
    Public Property radius As Double
    Public Property PowerLevel As String
    Public Property RandomProp As String
    <XmlAttribute("clientid")> Public Property clientid() As String


    Public Sub New()

    End Sub


End Class
<XmlRoot("Ball")>
Public Class ballColor
    <XmlElement("ballColor")> Public Property ballColor As String
    <XmlAttribute("transactionid")> Public Property transactionid As String
    Public Sub New()

    End Sub
End Class

所以我在表单上有实际的反序列化调用,但这似乎不是我的问题,因为当我运行它时,除了transactionid之外,每个属性都被正确填充。我做错了什么?

2 个答案:

答案 0 :(得分:3)

我宁愿将ballColor作为球内的属性。请尝试以下方法。

<Serializable>
<XmlRoot("Ball")>
Public Class Ball
    Public Property Name As String
    Public Property radius As Double
    Public Property PowerLevel As String
    Public Property RandomProp As String
    <XmlAttribute("clientid")> Public Property clientid() As String
    Public Property ballColor As ballColor

    Public Sub New()
        ballColor = New ballColor
    End Sub

End Class

<Serializable>
Public Class ballColor
    <XmlText> Public Property ballColor As String
    <XmlAttribute("transactionid")> Public Property transactionid As String

    Public Sub New()

    End Sub
End Class

答案 1 :(得分:1)

将ballColor类更改为:

Public Class ballColor

    <XmlAttribute("transactionid")> 
    Public Property transactionid As String   

    <XmlText> 
    Public Property Value As String
End Class

这会将transactionid中的属性ballcolor.transactionid值和ballcolor字段中的ballcolor.value值存储

更改主球类

Public Class Ball
  Public Property Name As String
    Public Property radius As Double
    Public Property PowerLevel As String
    Public Property RandomProp As String
    <XmlAttribute("clientid")> Public Property clientid() As String
    Public Property _ballColor As ballColor
End Class