linq - Dictionary to XML C# -


i have dictionary<tkey, tvalue> , want convert xml, using linq.

<root> <key>tkey1</key> <value>tvalue1</value> <key>tkey2</key> <value>tvalue2</value> <key>tkey3</key> <value>tvalue3</value> </root> 

right using var xdoc = new xdocument(new xelement("root", values.select(entry => new xelement(entry.key, entry.value))));

and getting

<root> <tkey1>tvalue1</tkey1> <tkey2>tvalue2</tkey2> <tkey3>tvalue3</tkey3> </root> 

as @alex mentioned, structure of desired xml not good, if need legacy system..

xdocument xdoc = new xdocument(         new xelement("root",             dictionary.selectmany(kvp => new []             {                 new xelement("key", kvp.key),                 new xelement("value", kvp.value)             }))); 

for sample dictionary

var dic = new dictionary<int, string> { [1] = "bob", [2] = "mike" }; 

result is

<root>   <key>1</key>   <value>bob</value>   <key>2</key>   <value>mike</value> </root> 

note: consider use better xml structure, easier read , parse, corresponds structure of dictionary. e.g.

<root>   <item key="1">bob</item>   <item key="2">mike</item> </root> 

now it's easy read , manipulate:

var item = (string)xdoc.xpathselectelement("//item[@key=2]"); // "mike" 

Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -