【发布时间】:2014-05-21 02:25:09
【问题描述】:
我有一个这样的 xml 文档:
<Tags>
<Key>
<Name>Model</Name>
<Value>Raggae</Value>
</Key>
<Key>
<Name>Rate</Name>
<Value>21</Value>
</Key>
</Tags>
我想从中创建一个字典,其中包含 Name 元素作为键,Value 元素作为值。
请帮帮我。
这是我写的代码,我想知道它是否足够高效:
IDictionary<string, string> XmlToDictionary(string data)
{
XElement rootElement = XElement.Parse(data);
var dict = new Dictionary<string, string>();
foreach (var el in rootElement.Elements())
{
if (el.Name.LocalName == "Key")
{
foreach (var sub in el.Elements())
{
string key = null;
string val = null;
if (sub.Name.LocalName == "Name") key = sub.Value;
if (sub.Name.LocalName == "Value") val = sub.Value;
if (key != null && !dict.ContainsKey(key)) dict.Add(key, val);
}
}
}
return dict;
}
【问题讨论】:
-
抱歉省略了代码
标签: c# asp.net xml linq xelement