Search code examples
c#xmllinqlinq-to-xmlxelement

How I can collect similar xml tag to groups with Xml.Linq in c#?


I have a xml file with this style

<all_elements>
    <elements>
            <element attribute="7" />
            <element attribute="1" />
            <element attribute="6" />
    </elements>
    <elements>
            <element attribute="2" />
            <element attribute="8" />
    </elements>
    .
    .
    .
</all_elements>

I want calculate average of each elements seprate with c# Xml.Linq, for exapmle:

average1= 4.66
average2= 5.00

I know that I must use XElement or XDocument type and use Query on XML and I can calculate sum & average of all element without consider top-level tag (elements), But I don't know how to calculate average of each elements...

How I can do this with with c# Xml.Linq? any Idea?


Solution

  • You need a nested query:

    root.Elements("elements").Select(
        e => e.Elements("element").Average(f => (int)f.Attribute("attribute"))
    )