Solved

c# turn string with xml into dictionary

Posted on 2014-02-17
2
1,929 Views
Last Modified: 2014-02-19
I have the string below as input.  How can I get a dictionary object out of it?  The parameters might change, which is why I want a dictionary.

var stringXml = "<width>100</width><height>200</height><controller>MyConttoller</controller>";

I have seen people mention ToDictionary but I could not figure out how to implement it based on this input.
0
Comment
Question by:jackjohnson44
2 Comments
 
LVL 52

Assisted Solution

by:Carl Tawn
Carl Tawn earned 250 total points
ID: 39865807
If you want to treat it as XML then you'll need to wrap a root node around it all. Then you can do something like:
var stringXml = "<settings><width>100</width><height>200</height><controller>MyConttoller</controller></settings>";
            
XDocument doc = XDocument.Parse(stringXml);
var dict = doc.Element("settings").Elements().Select(t => new { t.Name, t.Value }).ToDictionary(t => t.Name, t => t.Value.ToString());

Open in new window

0
 
LVL 23

Accepted Solution

by:
Michael74 earned 250 total points
ID: 39865853
For this solution your xml needs a root node which I have made as root and you also need the namespaces System.Xml, & System.Collections.Generic

         XmlDocument xmlDoc = new XmlDocument();
         xmlDoc.LoadXml(@"<root><width>100</width><height>200</height><controller>MyConttoller</controller></root>");
         Dictionary<string,string> dict = new Dictionary<string,string>();
         foreach (XmlElement node in xmlDoc.DocumentElement)
         {
            dict.Add(node.Name, node.InnerText);
         }

Open in new window

0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question