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!
Nguồn
2018-03-07 21:14:00
bạn có thể sử dụng ToDictionary ... * rootElement.Elements(). ToDictionary (key => key.Name, val => val.Value); * –
Còn giá trị XML lồng nhau thì sao? Ví dụ: " giá trị 1 value2 " –