[英]deserialize an eterogeneus xml file to a dictionary of objects in vb.net
I have an XML file like this: 我有一个像这样的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>
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...) 给我一个错误(我认为这是因为我无法使用动态设置的Type来初始化XmlSerializer对象,但看不到任何解决方案...)
I can also do nested dictionaries but I'm not sure exactly what you need. 我也可以做嵌套的字典,但是我不确定您到底需要什么。 Using Xml Linq : 使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.