简体   繁体   English

LINQ:C#中XML节点的总和

[英]LINQ: Sum values of XML nodes in C#

I have an XML document and I would like to sum all elements of a specific name. 我有一个XML文档,我想总结一个特定名称的所有元素。 How do I do this? 我该怎么做呢?

You can start with the following code, which sums the value of specificName elements anywhere in the document ( Descendants returns a collection of all elements with the specified name, regardless how deeply nested they are): 您可以从以下代码开始,该代码对文档中任何位置的specificName元素的值求和( Descendants返回具有指定名称的所有元素的集合,无论它们嵌套的深度如何):

var doc = XDocument.Load("doc.xml");
var sum = (from nd in doc.Descendants("specificName")
           select Int32.Parse(nd.Value)).Sum();

Alternatively, if you don't want to use the query syntax, you could write something like: 另外,如果您不想使用查询语法,则可以编写如下内容:

var sum = doc.Descendants("specificName").Sum(nd => 
            Int32.Parse(nd.Value));

The examples assume that the value is stored as a text inside the element and that it is an integer. 这些示例假定值以文本形式存储在元素内,并且它是整数。

Suppose this is your XML: 假设这是您的XML:

<nodes>
     <reading c='1'>17</reading>
     <reading c='2'>18</reading>
     <reading c='3'>19</reading>
     <reading c='4'>21</reading>
     <reading c='5'>4</reading>
     <reading c='6'>3</reading>
     <reading c='7'>7</reading>
</nodes>

Then use this code to sum the values of the reading elements: 然后,使用以下代码对reading元素的值求和:

public void Run()
{
    XDocument doc = XDocument.Load(fileToLoad);
    System.Console.WriteLine("\nSumming:");
    var sum = doc.Element("nodes")
                 .Elements("reading")
                 .Sum(n => int.Parse(n.Value));

    Console.WriteLine("  {0}", sum);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM