views:

57

answers:

1

I have the following XML:

<FootNotes>
  <Line id="10306" reference="*"></Line>
  <Line id="10308" reference="**"></Line>
  <Line id="10309" reference="***"></Line>
  <Line id="10310" reference="****"></Line>
  <Line id="10311" reference="+"></Line>
</FootNotes>

and I have the following code where I'm to get a Dictionary<int, string>() object into

myObject.FootNotes 

so that each Line is a Key/Value pair

var doc = XElement.Parse(xmlString);

var myObject = new
  {
      FootNotes = (from fn in doc
                       .Elements("FootNotes")
                       .Elements("Line")
                       .ToDictionary
                       (
                       column => (int) column.Attribute("id"),
                       column => (string) column.Attribute("reference")
                       )
                  )
  };

I am unsure how to get this from the XML into the object though. Can anyone suggest a solution?

+4  A: 

Your code is nearly correct. Try this slight variation instead:

FootNotes = (from fn in doc.Elements("FootNotes")
                           .Elements("Line")
             select fn).ToDictionary(
                 column => (int)column.Attribute("id"),
                 column => (string)column.Attribute("reference")
             )

I don't think the long from ... select syntax really helps much here. I'd use this slightly simpler code instead:

Footnotes = doc.Descendants("Line").ToDictionary(
                e => (int)e.Attribute("id"),
                e => (string)e.Attribute("reference")
            )

However you are using an anonymous type in your example code. You need to use a concrete type if you are planning to return this object to the caller.

var myObject = new SomeConcreteType
    {
        Footnotes = ....
    };
Mark Byers
the code is _almost_ correct, except for `(from fn in ` and the trailing `)`. The sample you provided before editing pointed this out. You should revert the last edit so I can select this as the correct answer
DaveDev
@DaveDev: I've actually added that now too :)
Mark Byers