MCooke
MCooke

Reputation: 25

Count the number of Attributes in an XML Element

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.

Research: http://social.msdn.microsoft.com/Forums/en-US/8379f0d4-a4f1-41ec-9f45-4573dba81efe/count-number-of-elements-and-attributes-using-linq

Upvotes: 1

Views: 4521

Answers (1)

CSJ
CSJ

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

Related Questions