使用LINQ从XML计算并获取子节点值的总和值

时间:2016-05-29 15:47:59

标签: c# xml linq count sum

这是我的XML文件,我正在使用C#和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. 我想得到每个personID的投票数,按ID分组,如:

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

  2. 我也希望获得这些投票的总和值,例如:

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

3 个答案:

答案 0 :(得分:1)

您可以将linq用于此

的Xml
    //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() 
        });

答案 1 :(得分:1)

使用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();

        }
    }
}

答案 2 :(得分:0)

您可以使用[XmlDocument][1]来解析XML,[XPath][1]选择要处理的节点,Linq来总结投票。或者,您可以使用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);
}