views:

518

answers:

1

Hi,

using xmltextreader, how would I load a hashtable.

XML:

<base><user name="john">2342343</user><user name="mark">239099393</user></base>

This was asked before but it was using some funky linq that I am not fully comfortable with just yet.

+2  A: 

Well, the LINQ to XML solution is really easy, so I suggest we try to make you comfortable with that instead of creating a more complex solution. Here's the code, with plenty of explanation...

// Load the whole document into memory, as an element
XElement root = XElement.Load(xmlReader);

// Get a sequence of users
IEnumerable<XElement> users = root.Elements("user");

// Convert this sequence to a dictionary...
Dictionary<string, string> userMap = users.ToDictionary(
      element => element.Attribute("name").Value, // Key selector
      element => element.Value);                 // Value selector

Of course you could do this all in one go - and I'd probably combine the second and third statements. But that's about as conceptually simple as it's likely to get. It would become more complicated if you wanted to put error handling around the possibility that a user element might not have a name, admittedly. (This code will throw a NullReferenceException in that case.)

Note that this assumes you want the name as the key and id as value. If you want the hashtable the other way round, just switch the order of the lambda expressions.

Jon Skeet
hmm..i'm getting a 'doesn't contain a definition or extension method for ToDictionary(..)' ? using asp.net 4.0
Blankman