Link to home
Start Free TrialLog in
Avatar of Tom Sage
Tom SageFlag for United States of America

asked on

.NET XML to Dictionary - XML has repeating node names

Hello,

I have an XML file with repeating node names that I need to load into a Dictionary(Of string, string).  See customer.xml attachment.

Here is the code I would like to use, but a Dictionary does not allow loading of repeated Keys.

    
Dim doc = XDocument.Load("customer.xml")

Dim dmap = doc.Descendants.ToDictionary(Function(e) e.Name.LocalName, Function(e) e.Value)

Open in new window


I thought of renaming the repeating nodes by appending a number to the name, like Tax1, Tax2, ...   Then running the code above.

Is there a better way to do this ?

Thank you
Customer.xml
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Why use a dictionary - as you have found it isn't really suitable with having duplicates.
You could use a List (or SortedList) for instance.
Avatar of Tom Sage

ASKER

Hi Andy,

I tried using a List(of string, string) since the xDoc.Descendants has a .ToList method, like this:

Open in new window

           Dim myList = doc.Descendants.ToList(Function(e) e.Name.LocalName & "," & Function(e) e.Value)

I kept getting the error:  Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type

I would like the output to be:  Field name, Value

Thanks
ASKER CERTIFIED SOLUTION
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I've just checked, the sorted list won't support duplicate keys either.  Either use a List or modify the keys as you thought originally and use a dictionary (but I suspect that would be a bad option - you add extra work just to force it into a dictionary)
I tested your suggestion and it is working great !

One final question - I am doing a loop through the XElements returned by xDocument.Descedants.  When I get a Parent node I get all the values from the children of that Parent.

Is there a way to know it is a Parent node and just get the name and not the values ?

Thank you
Not certain if this is suitable: if it has child elements then it is a 'parent' type of node
Andy,

I think I will close this issue.  I looked through intellisense for XElement and could not find a good test for a Parent node.  I will experiment myself.

Thank you for your excellent and prompt help !
Excellent and prompt help