简体   繁体   中英

Counting and get sum value of child node values from XML with LINQ

This is my XML file and I'm using C# and LINQ:

<?xml version="1.0" encoding="utf-8"?>
<Votes>
  <person id="1">
    <votes>9</votes>
    <votes>1</votes>
  </person>
  <person id="2">
    <votes>5</votes>
    <votes>6</votes>
  </person>
  <person id="3">
    <votes>5</votes>
    <votes>5</votes>
    <votes>2</votes>
    <votes>5</votes>
  </person>
</Votes>
  1. I want to get the number of votes for each personID, groupped by id, like:

    personID = 1, count = 2
    personID = 2, count = 2
    personID = 3, count = 4

  2. I also want to get the sum value of these votes, like:

    personID = 1, sum = 10
    personID = 2, sum = 11
    personID = 3, sum = 17

You can use linq to Xml for this

    //Your Xml string goes into _xml
    var doc = XDocument.Parse(_xml);

    var baseGrouping = doc.Descendants("Votes")
        .SelectMany(a=>a.Descendants()
        .Select(b=>new{ personId = a.Attribute("id").Value, vote = int.Parse(b.Value) }));

    var aggregates = baseGrouping.GroupBy(a=>a.personId)
        .Select(a=>new { 
                     personId=a.Key, 
                     count = a.Count(), 
                     sum = a.Sum() 
        });

Use xml linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\Test.xml";
        static void Main(string[] args)
        {
             XDocument doc = XDocument.Load(FILENAME);
            var results = doc.Descendants("person").Select(x => new {
                id = x.Attribute("id"),
                count = x.Elements("votes").Count(),
                sum = x.Elements("votes").Select(y => (int)y).Sum()
            }).ToList();

        }
    }
}

You can use a [XmlDocument][1] to parse the XML, [XPath][1] to select the nodes to process and Linq to sum up the votes. Alternatively you could use LINQ to XML .

https://dotnetfiddle.net/6HlU3s

XmlDocument doc = new XmlDocument();
doc.LoadXml("Your XML");

foreach (XmlNode person in doc.SelectNodes("//person"))
{
    int id = int.Parse(person.Attributes["id"].Value);
    List<int> votes = new List<int>();
    foreach (XmlNode node in person.SelectNodes("./votes"))
    {
        votes.Add(int.Parse(node.InnerText));
    }

    int voteCount = votes.Count;
    int voteSum = votes.Sum();

    Debug.WriteLine("Person {0}: {1} votes (sum {2})", id, voteCount, voteSum);
}

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