Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I load the following XML using LINQ-to-XML into a dictionary?

How can I load the following formatted XML document:

<Settings>
    <MimeTypes>
        <MimeType Type="application/mac-binhex40" Extensions=".hqx"/>
        <MimeType Type="application/msword" Extensions=".doc;.docx"/>
        <MimeType Type="application/pdf" Extensions=".pdf"/>
        <MimeType Type="application/vnd.ms-excel" Extensions=".xla;.xlc;.xlm;.xls;.xlt;.xlw;.xlsx"/>
    </MimeTypes> 
</Settings>

Into a dictionary where the key is an individual extension, and the value is the mimetype.

So, for this line:

<MimeType Type="application/vnd.ms-excel" Extensions=".xla;.xlc;.xlm;.xls;.xlt;.xlw;.xlsx"/>

I would have the following key-value entries:

Key: ".xla" Value: "application/vnd.ms-excel"
Key: ".xlc" Value: "application/vnd.ms-excel"
Key: ".xlm" Value: "application/vnd.ms-excel"
Key: ".xls" Value: "application/vnd.ms-excel"
Key: ".xlt" Value: "application/vnd.ms-excel"

I'm relatively new to the LINQ-To-XML business.

I know that I should load in the document into an XElement like:

 XElement settingsDoc = XElement.Load("Settings.xml");

However, how to do I select all "MimeType" entries?

like image 698
Rinndar Avatar asked Feb 01 '26 10:02

Rinndar


1 Answers

Something like:

 var dictionary = (from element in settingsDoc.Descendants("MimeType")
                   from extension in element.Attribute("Extensions")
                                         .Value.Split(';')
                   select new { Type = element.Attribute("Type").Value,
                                Extension = extension })
                   .ToDictionary(x => x.Extension,
                                 x => x.Type);
like image 132
Jon Skeet Avatar answered Feb 04 '26 00:02

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!