将eterogeneus xml文件反序列化为vb.net中的对象字典

时间:2018-07-19 11:30:20

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

我有一个像这样的XML文件:

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

我想反序列化为一个

Public Servers As New Dictionary(Of String, Object)

我正在尝试使用此代码

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

(我有一个“服务器”,“连接”和“本地”类) 但似乎

Dim serializer As New XmlSerializer(Nodetype)

给我一​​个错误(我认为是因为我无法使用动态设置的Type初始化XmlSerializer对象,但看不到任何解决方案...)

1 个答案:

答案 0 :(得分:0)

我也可以做嵌套字典,但是我不确定您到底需要什么。使用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