简体   繁体   English

将Dictionary <string,string>转换为xml的简便方法,反之亦然

[英]Easy way to convert a Dictionary<string, string> to xml and vice versa

Wondering if there is a fast way, maybe with linq?, to convert a Dictionary<string,string> into a XML document. 想知道是否有一种快速的方法,可能使用linq ?,将Dictionary<string,string>转换为XML文档。 And a way to convert the xml back to a dictionary. 还有一种将xml转换回字典的方法。

XML can look like: XML可以如下所示:

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

Dictionary to Element: 字典到元素:

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

Element to Dictionary: 元素到词典:

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

You can use DataContractSerializer. 您可以使用DataContractSerializer。 Code below. 代码如下。

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

Just use this for XML to Dictionary: 只需将此用于XML to Dictionary:

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

Dictionary to XML: 字典到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;
        }

The XML: XML:

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

You just pass the element UserTypes to that method and voila you get a dictionary with the coresponding keys and values and vice versa. 您只需将元素UserTypes传递给该方法,然后您将获得一个包含相应键和值的字典,反之亦然。 After converting a dictionary append the element to XDocument object and save it on the disk. 转换字典后,将元素附加到XDocument对象并将其保存在磁盘上。

Did something like this for an IDictionary 为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);
}

That produced the following XML: 这产生了以下XML:

<root>
  <parent id="2">0</parent>
  <parent id="24">1</parent>
  <parent id="25">2</parent>
  <parent id="3">3</parent>
</root>
  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();

I was looking for the same thing with a little difference(string, object) and I solved like this: 我正在寻找相同的东西,有点不同(字符串,对象),我这样解决了:

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

...for a dictionary(nested): ...对于字典(嵌套):

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

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

...passing "root" as firstNode i get: ...将“root”作为firstNode传递给我:

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

Edited! 编辑!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM