Reading XML to a Dictionary

后端 未结 2 712
有刺的猬
有刺的猬 2021-02-08 11:26

I need to read an XML file to a dictionary.

I read few guides and I only got confused from weird words that I don\'t understand (such as nodes, XML validation etc.). So,

2条回答
  •  萌比男神i
    2021-02-08 11:47

    var data = XElement.Parse(xml)
        .Elements("def")
        .ToDictionary(
            el => (int)el.Attribute("number"),
            el => (string)el.Attribute("name")
        );
    

    This:

    • parses the xml into an XElement (starting at )
    • iterates over the elements
    • forms a dictionary, using @number as the key (interpreting as an int), and @name as the value (as a string)
    • assigns this dictionary to data, which is implicitly typed as Dictionary

提交回复
热议问题