我正在尝试使用LINQ将 XML中的子子值放入字典集合中.我已经使用与XML相同结构的列表和自定义集合完成了此操作,但无法搜索特定值.如果我知道parentName,childName和subChildName,我希望能够找
key = "parentNameValue1.childNameValue1.subchildNameValue1.subChildProperty1" value = 0
我可以连接字符串以形成一个特定的键,并搜索该键以返回一个值.
XML:
<root>
<parent>
<parentName>parentNameValue1</parentName>
<child>
<childName>childNameValue1</childName>
<subchild>
<subchildName>subchildNameValue1</subchildName>
<subChildProperty1>0</subChildProperty1>
<subChildProperty2>5</subChildProperty2>
</subchild>
<subchild>
<subchildName>subchildNameValue2</subchildName>
<subChildProperty1>0</subChildProperty1>
<subChildProperty2>10</subChildProperty2>
</subchild>
</child>
</parent>
<root>
这个问题有点类似于" rel="nofollow" target="_blank">this question here,但我无法让代码在VB中运行我的应用程序.
我是SO(和VB)的新手,所以如果我的礼仪不正确,我会道歉.
有了VB.NET的优秀XML支持,这很容易做到:Imports System.Xml.Linq
...
Sub Main()
Dim xml = _
<root>
<parent>
<parentName>parentNameValue1</parentName>
<child>
<childName>childNameValue1</childName>
<subchild>
<subchildName>subchildNameValue1</subchildName>
<subChildProperty1>0</subChildProperty1>
<subChildProperty2>5</subChildProperty2>
</subchild>
<subchild>
<subchildName>subchildNameValue2</subchildName>
<subChildProperty1>0</subChildProperty1>
<subChildProperty2>10</subChildProperty2>
</subchild>
</child>
</parent>
</root>
' Alternatively, load XML from a file
' Dim xml = XDocument.Load(fileName)
Dim dict As New Dictionary(Of String, Integer)
' Extract the properties
For Each parent In xml.<parent>
Dim parentName = parent.<parentName>.Value
For Each child In parent.<child>
Dim childName = child.<childName>.Value
For Each subchild In child.<subchild>
Dim subchildName = subchild.<subchildName>.Value
For Each prop In subchild.Elements.Where(Function(e) e.Name <> "subchildName")
dict.Add(String.Format("{0}.{1}.{2}.{3}", parentName, childName, subchildName, prop.Name), _
Integer.Parse(prop.Value))
Next
Next
Next
Next
' Print the values, to show that we've done a good job
For Each kv In dict
Console.WriteLine("{0}: {1}", kv.Key, kv.Value)
Next
Console.ReadLine()
End Sub
(显然,代码假定Option Strict On和Option Infer On.)
