Reputation: 25
I've just started using LINQ though I have some experience using C#. Currently using LINQPad 4.
I'm trying to count the number of attributes in each element in an XML Document.
This is what ive got already, its a mixture of the samples within LINQPad and research done on the subject already. What I'm looking for is either a way to make this work or a better way of doing this.
XElement config = XElement.Parse (
@"<configuration>
<client enabled='1' enabled2='0' enabled3='1'>
<timeout>30</timeout>
</client>
<client enabled='true'>
<timeout>30</timeout>
<timeout>30</timeout>
</client>
</configuration>");
foreach (XElement child in config.Elements()){
Console.WriteLine("Start");
int attNumbers = config.Descendants().Attributes().Select(att => att.Name).Distinct(). Count();
Console.WriteLine(attNumbers);}
This solution only seems to count the maximum amount of attributes.
Any help would be greatly appreciated.
Upvotes: 1
Views: 4521
Reputation: 3941
I would do a loop over all elements in the document, then count the attributes on each:
foreach (var element in config.DescendantsAndSelf())
{
Console.WriteLine("{0}: {1} attributes",
element.Name,
element.Attributes().Count()
);
}
Upvotes: 5