2016-05-29 66 views
-1

这是我的XML文件,我使用C#和LINQ:计数和XML获得子节点值的总和值与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,计数= 2
    PERSONID = 2,计数= 2
    PERSONID = 3,计数= 4

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

    PERSONID = 1,总和= 10
    PERSONID = 2,总和= 11
    PERSONID = 3,总和= 17

回答

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

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