Convert XML to VB.NET Dictionary

I am trying to put child values ​​from XML into a dictionary collection using LINQ. I did this with lists and user collections that follow the same structure as XML, but I cannot find specific values. If I know parentName, childName and subChildName, I want to find subChildProperty1.value and subChildProperty2.value without iterating over the entire collection and each of the following subcategories, as I should do with lists. This may not be the best implementation, and I'm open to suggestions, but still would like to figure out how to do it. Then it will allow me to have a dictionary element:

key = "parentNameValue1.childNameValue1.subchildNameValue1.subChildProperty1" value = 0 

and I could just concatenate the strings to form a specific key and search on that key to return the value.

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> 

This question is somewhat similar to this question here , but I could not get the code working in VB for my application.

I'm new to SO (and VB), so I apologize if my etiquette is wrong.

+4
source share
1 answer

Thanks to the great support of XML VB.NET this is pretty easy to do:

 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 

(Obviously, the code assumes the option Strict On and Option Infer On.)

+4
source

Source: https://habr.com/ru/post/1414953/


All Articles