Reputation: 311
I have an XML like this:
<msg action="getDetails" class="2">
<stamps msgtime="4/15/2014" ltq="2014-04-15">
<dat la="get" />
</stamps>
</msg>
How can I retrieve Dictionary of all the attributes and their corresponding values? The expected output should look this:
action - getDetails
class - 2
msgtime - 4/15/2014
ltq - 2014-04-15
la - get
I can get it work for a particular level, but not for all child elements.
Upvotes: 2
Views: 4468
Reputation: 101681
var xDoc = XDocument.Load("path");
var attributes = xDoc.Descendants()
.SelectMany(x => x.Attributes())
.ToDictionary(x => x.Name.LocalName, x => (string)x);
Upvotes: 7
Reputation: 10865
Use Linq-to-XML
it is much easier to get the attribute and their values.
Sample usage
XElement cust = new XElement("PhoneNumbers",
new XElement("Phone",
new XAttribute("type", "home"),
"555-555-5555"),
new XElement("Phone",
new XAttribute("type", "work"),
"555-555-6666")
);
IEnumerable<XElement> elList =
from el in cust.Descendants("Phone")
select el;
foreach (XElement el in elList)
Console.WriteLine((string)el.Attribute("type"));
Upvotes: 0
Reputation: 19203
Have you tried using Descendants?
It would allow you to get an IEnumerable<XElement>
of all of the elements, getting the attributes is something you have already done it looks like.
Upvotes: 0