Quick way to parse an xml string (field/value pair) into Dictionary object in C# -


i have string containing field/value pairs in xml format , want parse dictionary object.

string param = "<fieldvaluepairs> <fieldvaluepair><field>name</field><value>books</value></fieldvaluepair> <fieldvaluepair><field>value</field><value>101 ways love</value></fieldvaluepair> <fieldvaluepair><field>type</field><value>system.string</value></fieldvaluepair> </fieldvaluepairs>"; 

is there quick , simple way read , store field/value pairs in dictionary object? no linq please.

also, there possibility value field can contain xml string itself. solutions provided wonderful fails if value xml iteself. example: if value like

<?xml version="1.0" encoding="utf-8"?><getcashflow xmlns="myservices"><inputparam><ac_unq_id>123123110</ac_unq_id></inputparam></getcashflow> 

it errors out message:

unexpected xml declaration. xml declaration must first node in document, , no white space characters allowed appear before it.

please feel free suggest modification in xml format if think can make things easier store in dictionary object.

using system; using system.linq; using system.xml.linq; using system.xml; using system.collections.generic; namespace consoleapplication1 {     class program     {         static void main(string[] args)         {             var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><r><a><k>key1</k><v><![cdata[<?xml version=\"1.0\" encoding=\"utf-8\"?><foo><bar>hahaha</bar></foo>]]></v></a><a><k>key2</k><v>value2</v></a></r>";               printdictionary(xmltodictionarylinq(xml));              printdictionary(xmltodictionarynolinq(xml));         }          private static dictionary<string, string> xmltodictionarynolinq(string xml)         {             var doc = new xmldocument();             doc.loadxml(xml);              var nodes = doc.selectnodes("//a");              var result = new dictionary<string, string>();             foreach (xmlnode node in nodes)             {                 result.add(node["k"].innertext, node["v"].innertext);             }              return result;         }          private static dictionary<string, string> xmltodictionarylinq(string xml)         {             var doc = xdocument.parse(xml);             var result =                 (from node in doc.descendants("a")                  select new { key = node.element("k").value, value = node.element("v").value })                 .todictionary(e => e.key, e => e.value);             return result;         }          private static void printdictionary(dictionary<string, string> result)         {             foreach (var in result)             {                 console.writeline("key: {0}, value: {1}", i.key, i.value);             }         }     } } 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -