Easy way to convert a Dictionary to xml and vice versa

前端 未结 6 1633
北海茫月
北海茫月 2020-11-30 22:13

Wondering if there is a fast way, maybe with linq?, to convert a Dictionary into a XML document. And a way to convert the xml back to a di

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 23:08

    Just use this for XML to Dictionary:

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

    Dictionary to XML:

     public static XElement DictToXml
                      (Dictionary inputDict, string elmName, string valuesName)
            {
    
                XElement outElm = new XElement(elmName);
    
                Dictionary.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;
            }
    

    The XML:

    
      
        
        
        
      
    
    

    You just pass the element UserTypes to that method and voila you get a dictionary with the coresponding keys and values and vice versa. After converting a dictionary append the element to XDocument object and save it on the disk.

提交回复
热议问题