简体   繁体   中英

Getting the name of the node and its corresponding values in xml using linq to xml in c#?

I want to get the name of the node and its corresponding values in a xml file using linq to xml.

I usually do this line of code to get the value of the node and store it in a list

var qry = from c in XElement.Load(commonpath).Elements("Root") select c;

        List<string> result = new List<string>();
        foreach (var i in qry)
        {
            result.Add(Convert.ToString(i));
        }

But now I want both node name and value to store it in a dictionary

Dictionary<string, double> amount = new Dictionary<string, double>();
        var qry = "";//what query here
        foreach(var i in qry)
        {
            amount.Add("Node Name", "Value");
        }

So what is the right query for this situation please help. Thanks

I hope this is what you are looking for:

    var doc = XDocument.Parse(@"
         <root>
            <firstname>Lucas</firstname>
            <lastname>Ontivero</lastname>
         </root>");
    var qry = from element in doc.Element("root").Descendants() select element;
    var result = qry.ToDictionary(e => e.Name, e => e.Value);
    result.ToList().ForEach(x=> Console.WriteLine("{0}:{1}", x.Key, x.Value ));

It prints:

firstname:Lucas
  lastname:Ontivero

Let me know if it is useful. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM