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

mrb*_*lah 39 c# xml linq dictionary

想知道是否有一种快速的方法,可能使用linq ?,将一个Dictionary<string,string>转换为XML文档.还有一种将xml转换回字典的方法.

XML可以如下所示:

<root>
      <key>value</key>
      <key2>value</key2>
</root>
Run Code Online (Sandbox Code Playgroud)

Lor*_*nVS 85

字典到元素:

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

元素到词典:

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 你可以使用ToDictionary ...*rootElement.Elements().ToDictionary(key => key.Name,val => val.Value);* (20认同)

dcp*_*dcp 12

您可以使用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();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)


Nik*_*lay 6

只需将此用于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;
        }
Run Code Online (Sandbox Code Playgroud)

字典到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;
        }
Run Code Online (Sandbox Code Playgroud)

XML:

<root>
  <UserTypes>
    <Type key="Administrator" value="A"/>
    <Type key="Affiliate" value="R" />
    <Type key="Sales" value="S" />
  </UserTypes>
</root>
Run Code Online (Sandbox Code Playgroud)

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


Vai*_*hav 5

为 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);
}
Run Code Online (Sandbox Code Playgroud)

这产生了以下 XML:

<root>
  <parent id="2">0</parent>
  <parent id="24">1</parent>
  <parent id="25">2</parent>
  <parent id="3">3</parent>
</root>
Run Code Online (Sandbox Code Playgroud)