简体   繁体   中英

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?

You need a nested query:

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

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