Sérialisation XML de collection d'Objets
Bonjour à tous,
J'ai un souci avec la sérialisation d'une collection qui contient elle même des collections.
J'ai donc une collection:
Code:
Public ListData As New List(Of clsData)
clsData se présente sous la forme:
Code:
1 2 3 4 5 6 7 8 9 10 11
|
Public Class clsData
Public Property NumberKey As String = ""
Public Property NumberCmd As String = ""
Public Property NumberUpd As String = ""
Public Property NameCustomer As String = ""
Public Property Article As New List(Of String) From {""}
Public Property SoftWare As New List(Of String) From {""}
Public Property Level As New List(Of String) From {""}
End Class |
Pour créer mon XML pas de souci mais un détail quand même que j'explique après:
Code:
1 2 3 4 5 6 7 8 9 10 11
|
Public SubWriteFile(ByVal MyFile As String)
Dim wr As StreamWriter
Dim xs As XmlSerializer
'Serialisation XML
wr = New StreamWriter(MyFile)
xs = New XmlSerializer(GetType(List(Of clsData)), New XmlRootAttribute("Lic"))
xs.Serialize(wr, ListData)
WriteFile = True
wr.Close()
End Sub |
J'ai bien sur épuré ici le code des vérifications nécessaires.
Donc tout se passe bien, cela me créer mon fichier XML avec un détail cependant.:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
<?xml version="1.0" encoding="utf-8"?>
<Lic xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<clsData>
<NumberKey>123456789</NumberKey>
<NumberCmd>80000</NumberCmd>
<NumberUpd>1</NumberUpd>
<NameCustomer>MonEntreprise</NameCustomer>
<Article>
<string />
<string>B00123466789</string>
<string>B00987654321</string>
</Article>
<SoftWare>
<string />
<string>MonLogiciel1</string>
<string>MonLogiciel2</string>
</SoftWare>
<Level>
<string />
<string>User</string>
<string>Admin</string>
</Level>
</clsData>
</Lic |
Ici avec l'exemple d'une seule entrée qui comporte 2 sous ensembles, Articles/SoftWare/Level, mais si j'en rentre plusieurs, pas de souci.
Par contre comme vous pouvez constater j'ai 2 objets(sous ensemble) dans Articles, SoftWare et Level, mais il m'en met 3 avec le 1er vide.
Jusque là, après le fait qu'il me met 3 objets au lieu de 2 cela me va, par contre a la relecture j'ai un souci.
Relecture du fichier XML avec cette méthode:
Code:
1 2 3 4 5 6 7 8 9
|
Public Sub OpenData(ByVal MyFile As String)
Dim xs As XmlSerializer
'deserialisation
xs = New XmlSerializer(GetType(List(Of clsData)), New XmlRootAttribute("Lic"))
Using stream = New System.IO.StreamReader(MyFile)
ListData = CType(xs.Deserialize(stream), List(Of clsData))
End Using
End Sub |
La lecture ce passe bien mais lorsque je regarde ListData, il m'indique bien que mes collections Articles/SoftWare/Level ont 2 éléments mais je n'est que le dernier de renseigné, les autres sont vides.
Idem si j'en met 5 ou 6 sous ensemble, j'ai toujours que le dernier de renseigné.
Avez vous une idée ?
Merci de votre aide