Easy way to convert a Dictionary to xml and vice versa

前端 未结 6 1625
北海茫月
北海茫月 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:09

    I was looking for the same thing with a little difference(string, object) and I solved like this:

    public static XElement ToXML(this Dictionary dic, string firstNode)
    {
        IList xElements = new List();
    
        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))
        {
            IList xElements = new List();
            foreach (var item2 in item as Dictionary)
                xElements.Add(new XElement(item2.Key, GetXElement(item2.Value)));
    
            return xElements.ToArray();
        }
    
        return item;
    }
    

    ...for a dictionary(nested):

    var key2 = new Dictionary
                    {
                        {"key3", "value"},
                        {"key4", "value"},
                    };
    
    var key = new Dictionary
                    {
                        {"key", "value"}
                        {"key2", key1},
                    };
    

    ...passing "root" as firstNode i get:

    
        value
        
            value
            value
        
    
    

    Edited!

提交回复
热议问题