Easy way to convert a Dictionary to xml and vice versa

前端 未结 6 1627
北海茫月
北海茫月 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 22:52

    You can use DataContractSerializer. Code below.

        public static string SerializeDict()
        {
            IDictionary dict = new Dictionary();
            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();
                }
            }
        }
    

提交回复
热议问题