2009-11-25 29 views

Trả lời

73

điển để Element:

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

Yếu tố để từ điển:

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

bạn có thể sử dụng ToDictionary ... * rootElement.Elements(). ToDictionary (key => key.Name, val => val.Value); * –

+0

Còn giá trị XML lồng nhau thì sao? Ví dụ: " giá trị 1 value2" –

10

Bạn có thể sử dụng DataContractSerializer. Mã dưới đây.

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

Did một cái gì đó như thế này cho một 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); 
} 

Đó sản xuất XML sau:

<root> 
    <parent id="2">0</parent> 
    <parent id="24">1</parent> 
    <parent id="25">2</parent> 
    <parent id="3">3</parent> 
</root> 
6

Chỉ cần sử dụng này cho XML vào Từ điển:

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

điển thành 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; 
     } 

XML:

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

Bạn chỉ cần vượt qua UserTypes yếu tố phương pháp đó và thì đấy bạn sẽ có được một cuốn từ điển với các phím coresponding và các giá trị và ngược lại. Sau khi chuyển đổi một từ điển gắn thêm phần tử vào đối tượng XDocument và lưu nó vào đĩa.

+0

Lỗi nhỏ trong DictToXml(). Đây là một phiên bản sửa chữa cho vòng lặp. [code] foreach (chuỗi khóa trong khóa) { XElement inner = new XElement (valuesName); inner.Add (new XAttribute ("key", key)); inner.Add (new XAttribute ("value", inputDict [key])); outElm.Thêm (bên trong); } [/ code] –

2
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(); 
+0

Tôi đã sử dụng gói NewtonSoft.Json cho JsonConvert –

+0

nó sẽ cung cấp dữ liệu định dạng xml hoặc dữ liệu tệp json. –

1

tôi đang tìm kiếm điều tương tự với một sự khác biệt nhỏ (string, object) và tôi giải quyết như thế này:

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

... cho một cuốn từ điển (lồng):

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

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

... đi "gốc" như firstNode tôi nhận được:

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

Đã chỉnh sửa!

Các vấn đề liên quan