简体   繁体   中英

deserialize an eterogeneus xml file to a dictionary of objects in vb.net

I have an XML file like this:

<server>
    <Server name="Mail">
        <address></address>
        <host></host>
        <name></name>
    </Server>
    <Connection name="autentication">
        <IPServer>127.0.0.1</IPServer>
        <Database></Database>
        <User></User>
        <Password></Password>
    </Connection>
    <Local name="local">
        <version></version>
        <file></file>
    </Local>
</server>

which I want to deserialize to a

Public Servers As New Dictionary(Of String, Object)

I'm trying with this code

Public Sub LoadServersDictionary(ByRef dict As Dictionary(Of String, Object), Optional ByVal XMLFilePath As String = "server.xml")
    Dim doc As New XmlDocument
    Dim nodereader As XmlNodeReader
    Dim newdictKey As String
    doc.Load(XMLFilePath)
    For Each Node As XmlNode In doc.DocumentElement.ChildNodes
        Dim Nodetype As Type = Type.GetType(Node.Name)
        MsgBox(Node.Name)
        Dim serializer As New XmlSerializer(Nodetype)
        newdictKey = Node.Attributes("name").InnerText
        nodereader = New XmlNodeReader(Node)
        dict.Add(newdictKey, serializer.Deserialize(nodereader))
    Next
End Sub

(I have a "Server", a "Connection", and a "Local" Class) but it seems like

Dim serializer As New XmlSerializer(Nodetype)

is giving me an error (I think it's because I cannot use a dynamically set Type to initialize an XmlSerializer Object, but I can't see any solution...)

I can also do nested dictionaries but I'm not sure exactly what you need. Using Xml Linq :

Imports System.Xml
Imports System.Xml.Linq
Module Module1
    Const FILENAME As String = "c:\temp\test.xml"
    Sub Main()
        Dim doc As XDocument = XDocument.Load(FILENAME)

        Dim dict As Dictionary(Of String, String) = doc.Descendants("server").FirstOrDefault().Elements() _
                                                    .GroupBy(Function(x) x.Name.LocalName, Function(y) y.Attribute("name").Value) _
                                                    .ToDictionary(Function(x) x.Key, Function(y) y.FirstOrDefault())

    End Sub

End Module

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM