[英]How can I load the following XML using LINQ-to-XML into a dictionary?
如何加载以下格式化的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”条目?
就像是:
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);
这是我的解决方案。
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);
这是我的贡献。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.