我如何可以加载使用LINQ到XML转换成字典以下XML?转换成、字典、加载、XML

2023-09-03 13:51:35 作者:只愿你好

我如何加载以下格式的XML文档:

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>

成一本字典,其中的关键是个人的扩展,其值是MIMETYPE。

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:

键:.xla价值:应用程序/ vnd.ms-Excel的 键:.xlc价值:应用程序/ vnd.ms-Excel的 键:.xlm工作的价值:应用程序/ vnd.ms-Excel的 键:.xls的价值:应用程序/ vnd.ms-Excel的 键:名为.xlt的价值:应用程序/ vnd.ms-Excel的

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"

我是比较新的LINQ到XML的业务。

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

我知道我应该在文件中加载到像的XElement:

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

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

然而,怎么做我选择所有Mime类型项?

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

推荐答案

是这样的:

 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);