How to create a dictionary <int, string> via LINQ to XML?

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 should get the object Dictionary<int, string>()in

myObject.FootNotes 

so each row 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 not sure how to get this from XML to an object. Can anyone suggest a solution?

+3
source share
1 answer

Your code is almost correct. Try this small change:

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 that the long syntax from ... selectreally helps a lot here. Instead, I would use this simpler code:

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

. , .

var myObject = new SomeConcreteType
    {
        Footnotes = ....
    };
+6

Source: https://habr.com/ru/post/1745309/


All Articles