2013-03-26 112 views
1

我無法將xml屬性反序列化到類屬性中。Vb.Net XmlDeseralize 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。我究竟做錯了什麼??

回答

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

耶!!!這工作,你搖滾!非常感謝 – Brandon 2013-03-26 15:17:27

1

您ballColor類改成這樣:

Public Class ballColor 

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

    <XmlText> 
    Public Property Value As String 
End Class 

這將存儲屬性在ballcolor.transactionidtransactionid值和ballcolor.value

改變主球類ballcolor

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

感謝您的幫助!但是...我不得不將值作爲(List of String),因爲如果我沒有創建我的XmlSerializer對象,它會引發錯誤。當我調試時,我不再有我應該在ballColor(現在稱爲Value)中的'White'值,並且transactionid仍然是'Nothing':( – Brandon 2013-03-26 15:12:09

+0

@BrandonJ查看更新回答 – 2013-03-26 15:16:00

+0

非常感謝,你和Icidis都給了我同樣的解決方案,但我會給Icidis的答案,因爲我看到他的第一個,你比他有7400點多,但再次感謝! – Brandon 2013-03-26 15:32:23