简体   繁体   English

从名称不同的xml节点获取相同属性的总和

[英]Get the sum of the same attribute from differently named xml nodes

I have an xml file as such 我有这样的xml文件

<root>
<segmentNameA attributeName="10" />
<segmentNameB attributeName="50" />
</root>

Here's my code: 这是我的代码:

XPathDocument xPathDocument = new XPathDocument(analysisFileToProcess);
XPathNavigator  Navigator = xPathDocument.CreateNavigator();

I would like to get the sum of all the attributeName attributes (10 + 50). 我想获取所有attributeName属性的总和(10 + 50)。

Here's what I do 这是我的工作

var sum /*want to obtain 60*/ = Navigator.Select(Navigator.Compile("sum(/root/*[self::segmentNameA or self::segmentNameB]/@attributeName)"));

I get an expression "has an invalid token". 我得到一个表达式“具有无效的令牌”。

However, when I do this 但是,当我这样做时

var nodes = Navigator.Select(Navigator.Compile("/root/*[self::segmentNameA or self::segmentNameB]"));

I get all the nodes which contain the attribute I'd like to sum on. 我得到了所有包含我要总结的属性的节点。

And when I do that 当我这样做时

var nodes = Navigator.Select(Navigator.Compile("/root/*[self::segmentNameA or self::segmentNameB]/@attributeName"));

I get the list of the attributes. 我得到了属性列表。 Why can't I use the sum function on this? 为什么不能在此上使用sum函数?

Could someone please point out to me what I am doing wrong? 有人可以向我指出我做错了什么吗?

It happens, because XPath expression must evaluate to a node-set. 之所以会这样,是因为XPath表达式必须计算为节点集。
Use Evaluate method instead: 改用Evaluate方法:

var sum = (double)Navigator.Evaluate("sum(/root/*[self::segmentNameA or self::segmentNameB]/@attributeName)");

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

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