如何加载以下格式化的XML文档:
<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。
所以,对于这一行:
<MimeType Type="application/vnd.ms-excel" Extensions=".xla;.xlc;.xlm;.xls;.xlt;.xlw;.xlsx"/>
我将拥有以下键值条目:
键:“。xla”值:“application / vnd.ms-excel”
键:“。xlc”值:“application / vnd.ms-excel”
键:“。xlm”值:“application / vnd.ms-excel”
键:“。xls”值:“application / vnd.ms-excel”
键:“。xlt”值:“application / vnd.ms-excel”
我对LINQ-To-XML业务相对较新。
我知道我应该将文档加载到XElement中,如:
XElement settingsDoc = XElement.Load("Settings.xml");
但是,如何选择所有“MimeType”条目?
答案 0 :(得分:5)
类似的东西:
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);
答案 1 :(得分:0)
这是我的解决方案。
XElement el = XElement.Parse(txt);
var mimeTypes = el.Element("MimeTypes").Elements("MimeType");
var transFormed = mimeTypes.Select(x =>
new
{
Type = x.Attribute("Type").Value,
Extensions = x.Attribute("Extensions").Value.Split(';')
}
);
Dictionary<string, string> mimeDict = new Dictionary<string, string>();
foreach (var mimeType in transFormed)
{
foreach (string ext in mimeType.Extensions)
{
if (mimeDict.ContainsKey(ext))
mimeDict[ext] = mimeType.Type;
else
mimeDict.Add(ext, mimeType.Type);
}
}
好的,看完Jonh的代码后......这是我的第二个解决方案:)
XElement el = XElement.Parse(txt);
var mimeTypes = el.Element("MimeTypes").Elements("MimeType");
var dictionary = mimeTypes.SelectMany(x => x.Attribute("Extensions").Value.Split(';').Select(
ext => new
{
Key = ext,
Value = x.Attribute("Type").Value
}
)
).ToDictionary( x => x.Key, y => y.Value);
答案 2 :(得分:0)
这是我的贡献。
Dictionary<string, string> dic = new Dictionary<string,string>();
foreach (XElement element in settingsDoc.Descendants("MimeType"))
{
string val = element.Attribute("Type").Value;
foreach (string str in element.Attribute("Extensions").Value.Split(';'))
if (!dic.ContainsKey(str)) dic.Add(str, val);
}