我有一个这样的 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;
}
最佳答案
我确定可能有更优雅的解决方案,但可以这样做:
函数
IDictionary<string, string> XmlToDictionary(string data)
{
XElement rootElement = XElement.Parse(data);
var names = rootElement.Elements("Key").Elements("Name").Select(n => n.Value);
var values = rootElement.Elements("Key").Elements("Value").Select(v => v.Value);
var list = names.Zip(values, (k, v) => new { k, v }).ToDictionary(item => item.k, item => item.v);
return list;
}
测试
var xmlString = @"<Tags>
<Key>
<Name>Model</Name>
<Value>Raggae</Value>
</Key>
<Key>
<Name>Rate</Name>
<Value>21</Value>
</Key>
</Tags>";
Console.WriteLine(XmlToDictionary(xmlString));
关于c# - ASP.NET 将 xml 字符串转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22936216/