【问题标题】:ASP.NET convert xml string to dictionaryASP.NET 将 xml 字符串转换为字典
【发布时间】: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


【解决方案1】:

我确信可能有更优雅的解决方案,但这样做可以:

功能

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

【讨论】:

    猜你喜欢
    • 2011-01-10
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    相关资源
    最近更新 更多