roi972
roi972

Reputation: 70

Linq To Xml - Create Dictionary From Repetitive XML

I have an XML string like this:

<root>
  <name>Key</name>
  <value>Value</value>
  <name>Key</name>
  <value>Value</value>
  <name>Key</name>
  <value>Value</value>
</root>

How can I produce a C# dictionary that corresponds to this - i.e for each pair of name and value create a dictionary item. (with use of Linq To XML).

Upvotes: 2

Views: 846

Answers (2)

ColinE
ColinE

Reputation: 70142

I would try something like this ...

XDocument doc = XDocument.parse(... parse you XML here ...);
var nameElements = doc.Descendants("name");
var dictionary = nameElements.ToDictionary(el => el.Value,
                                           el => el.ElementsAfterSelf().First().Value);

This first finds all the name elements, then projects this array to a dictionary. The key selector uses el.Value, which is the value of the name element. The value selector takes the next sibling of the element, which will be your value element.

Upvotes: 1

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262979

You can use ToDictionary():

var dict = XElement.Parse(yourMarkup).Elements("name").ToDictionary(
    name => name.Value,
    name => name.ElementsAfterSelf("value").First().Value);

Upvotes: 0

Related Questions