Linq xml to dictionary help

M

mickieparis

Hello, I hope someone can help me. I need to load an xml element to a
dictionary using the attribute as the key. Here is a sample of the
xml.
<Colors>
....
<FlagColors>
<USA>
<red order="0"/>
<white order="1"/>
<blue order="2"/>
</USA>
</FlagColors>
</Colors>

I need a sorted list or a dictionary so the colors are in a specific
order. For example in the USA the colors need to be ordered red
first, white second and blue third. So I need to use the order
attribute as the key for the dictionary and the element value as the
value in the dictionary.

I've been playing around with no success. I hope someone knows how to
do this.

Thanks,
Michelle
 
A

Arne Vajhøj

Hello, I hope someone can help me. I need to load an xml element to a
dictionary using the attribute as the key. Here is a sample of the
xml.
<Colors>
...
<FlagColors>
<USA>
<red order="0"/>
<white order="1"/>
<blue order="2"/>
</USA>
</FlagColors>
</Colors>

I need a sorted list or a dictionary so the colors are in a specific
order. For example in the USA the colors need to be ordered red
first, white second and blue third. So I need to use the order
attribute as the key for the dictionary and the element value as the
value in the dictionary.

I've been playing around with no success. I hope someone knows how to
do this.

Given that keys seems to go 0..N then why not use List<> instead
of Dictionary<>?

Arne
 
A

Arne Vajhøj

Given that keys seems to go 0..N then why not use List<> instead
of Dictionary<>?

Well if you want the Dictionary<> then here are some code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace E
{
public class Program
{
public static void Main(string[] args)
{
string s = @"<Colors>
<FlagColors>
<USA>
<red order='0'/>
<white order='1'/>
<blue order='2'/>
</USA>
</FlagColors>
</Colors>";
XDocument doc = XDocument.Parse(s);
Dictionary<int, string> dic =
doc.Element("Colors").Element("FlagColors").Element("USA").Elements().ToDictionary(elm
=> int.Parse(elm.Attribute("order").Value), elm => elm.Name.LocalName);
foreach(KeyValuePair<int, string> kvp in dic)
{
Console.WriteLine(kvp.Key + " = " + kvp.Value);
}
Console.ReadKey();
}
}
}

Arne
 
M

mickieparis

Thanks so much Arne! I was using Root.Descendants() and it wasn't
picking up the elements. Now I know to
use .Element("whatever").Element("whatever")....Elements() to get to
the level of the elements I need to extract. Thanks again.

Michelle
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top