【问题标题】:Easy way to convert a Dictionary<string, string> to xml and vice versa将 Dictionary<string, string> 转换为 xml 的简单方法,反之亦然
【发布时间】:2009-11-25 20:34:18
【问题描述】:

想知道是否有一种快速的方法(可能使用 linq?)将 Dictionary&lt;string,string&gt; 转换为 XML 文档。以及一种将 xml 转换回字典的方法。

XML 可能如下所示:

<root>
      <key>value</key>
      <key2>value</key2>
</root>

【问题讨论】:

    标签: c# xml linq dictionary


    【解决方案1】:

    字典到元素:

    Dictionary<string, string> dict = new Dictionary<string,string>();
    XElement el = new XElement("root",
        dict.Select(kv => new XElement(kv.Key, kv.Value)));
    

    元素到字典:

    XElement rootElement = XElement.Parse("<root><key>value</key></root>");
    Dictionary<string, string> dict = new Dictionary<string, string>();
    foreach(var el in rootElement.Elements())
    {
       dict.Add(el.Name.LocalName, el.Value);
    }
    

    【讨论】:

    • 你可以使用 ToDictionary... rootElement.Elements().ToDictionary(key => key.Name, val => val.Value);
    • 嵌套的 XML 值怎么样?例如:“value 1value2
    【解决方案2】:

    您可以使用 DataContractSerializer。代码如下。

        public static string SerializeDict()
        {
            IDictionary<string, string> dict = new Dictionary<string, string>();
            dict["key"] = "value1";
            dict["key2"] = "value2";
            // serialize the dictionary
            DataContractSerializer serializer = new DataContractSerializer(dict.GetType());
    
            using (StringWriter sw = new StringWriter())
            {
                using (XmlTextWriter writer = new XmlTextWriter(sw))
                {
                    // add formatting so the XML is easy to read in the log
                    writer.Formatting = Formatting.Indented;
    
                    serializer.WriteObject(writer, dict);
    
                    writer.Flush();
    
                    return sw.ToString();
                }
            }
        }
    

    【讨论】:

      【解决方案3】:

      只需将它用于 XML 到字典:

           public static Dictionary<string, string> XmlToDictionary
                                              (string key, string value, XElement baseElm)
              {
                  Dictionary<string, string> dict = new Dictionary<string, string>();
      
                  foreach (XElement elm in baseElm.Elements())
                  { 
                      string dictKey = elm.Attribute(key).Value;
                      string dictVal = elm.Attribute(value).Value;
      
                      dict.Add(dictKey, dictVal);
      
                  }
      
                  return dict;
              }
      

      字典到 XML:

       public static XElement DictToXml
                        (Dictionary<string, string> inputDict, string elmName, string valuesName)
              {
      
                  XElement outElm = new XElement(elmName);
      
                  Dictionary<string, string>.KeyCollection keys = inputDict.Keys;
      
                  XElement inner = new XElement(valuesName);
      
                  foreach (string key in keys)
                  {
                      inner.Add(new XAttribute("key", key));
                      inner.Add(new XAttribute("value", inputDict[key]));
                  }
      
                  outElm.Add(inner);
      
                  return outElm;
              }
      

      XML:

      <root>
        <UserTypes>
          <Type key="Administrator" value="A"/>
          <Type key="Affiliate" value="R" />
          <Type key="Sales" value="S" />
        </UserTypes>
      </root>
      

      您只需将元素 UserTypes 传递给该方法,瞧,您会得到一个包含相应键和值的字典,反之亦然。转换字典后,将元素附加到 XDocument 对象并将其保存在磁盘上。

      【讨论】:

      • DictToXml() 中的小错误。这里是循环的更正版本。 [代码] foreach(键中的字符串键){ XElement inner = new XElement(valuesName); inner.Add(new XAttribute("key", key)); inner.Add(new XAttribute("value", inputDict[key])); outElm.Add(inner); } [/code]
      【解决方案4】:

      为 IDictionary 做了类似的事情

      XElement root = new XElement("root");
      
      foreach (var pair in _dict)
      {
          XElement cElement = new XElement("parent", pair.Value);
          cElement.SetAttributeValue("id", pair.Key);
          el.Add(cElement);
      }
      

      生成了以下 XML:

      <root>
        <parent id="2">0</parent>
        <parent id="24">1</parent>
        <parent id="25">2</parent>
        <parent id="3">3</parent>
      </root>
      

      【讨论】:

        【解决方案5】:
          Dictionary<string, string> myDictionary = new Dictionary<string, string>();
          myDictionary.Add("key", "value");
          myDictionary.Add("key2", "value");
          var myJson = JsonConvert.SerializeObject(myDictionary);
          var myXml = JsonConvert.DeserializeXNode(myJson.ToString(),"root");
          Console.WriteLine(myXml.ToString());
          Console.Read();
        

        【讨论】:

        • 我已经为 JsonConvert 使用了 NewtonSoft.Json 包
        • 它会给一个xml格式的数据或json文件数据。
        【解决方案6】:

        我正在寻找相同的东西,但有一点不同(字符串,对象),我解决了这样的问题:

        public static XElement ToXML(this Dictionary<string, object> dic, string firstNode)
        {
            IList<XElement> xElements = new List<XElement>();
        
            foreach (var item in dic)
                xElements.Add(new XElement(item.Key, GetXElement(item.Value)));
        
            XElement root = new XElement(firstNode, xElements.ToArray());
        
            return root;
        }
        
        private static object GetXElement(object item)
        {
            if (item != null && item.GetType() == typeof(Dictionary<string, object>))
            {
                IList<XElement> xElements = new List<XElement>();
                foreach (var item2 in item as Dictionary<string, object>)
                    xElements.Add(new XElement(item2.Key, GetXElement(item2.Value)));
        
                return xElements.ToArray();
            }
        
            return item;
        }
        

        ...对于字典(嵌套):

        var key2 = new Dictionary<string, object>
                        {
                            {"key3", "value"},
                            {"key4", "value"},
                        };
        
        var key = new Dictionary<string, object>
                        {
                            {"key", "value"}
                            {"key2", key1},
                        };
        

        ...传递“root”作为我得到的第一个节点:

        <root>
            <key>value</key>
            <key2>
                <key3>value</key3>
                <key4>value</key4>
            </key2>
        </root>
        

        已编辑!

        【讨论】:

          【解决方案7】:

          @LorenVS 已经回答了 Xml 的字典

          但是我发现使用 Linq 的字典缺少答案 XML:

           // this could be XElement.Parse("<object attr='attr1'>value</object>") but lets do a file read, for more variety.
           var doc = new XmlDocument();
           doc.Load(fileName); 
           //also lets read attribiute and value as it hasnt been done above aswell.
           Dictionary<string, string> dict = 
           doc.DocumentElement.ChildNodes.OfType<XmlElement>()
              .ToDictionary(o => o.GetAttribute("attr"), o => o.Value)); 
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-05-14
            • 2021-05-19
            • 1970-01-01
            • 1970-01-01
            • 2015-01-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多