这个问题与以下内容完全相同:
C#中两个XPath表达式相乘的总和[关闭]我有xml。 我使用以下XPath表达式:
sum(//Item[@type='sg_aml_rel'][(./sg_percentage * ./related_id/Item[@type='sg_aml2']/sg_cost)])
我已经创建了XMLDoucment和Load XML对象,然后创建了XPathNavigator对象,并提供了xpth来评估XPathNavigator的方法。 我的XML看起来像:
<AML> <Item> <sg_percentage>10</sg_percentage> <related_id> <Item> <sg_cost>100<sg_cost> </Item> <related_id> </Item> <Item> <sg_percentage>20</sg_percentage> <related_id> <Item> <sg_cost>500<sg_cost> </Item> <related_id> </Item> <AML>我想要SUM(sg_percentage * sg_cost)。
This question is an exact duplicate of:
Sum of multiplication of two XPath expressions in C# [closed]I am have xml . I using following XPath expression:
sum(//Item[@type='sg_aml_rel'][(./sg_percentage * ./related_id/Item[@type='sg_aml2']/sg_cost)])
I have created object of XMLDoucment and Load XML into it then created XPathNavigator object and provide xpth to evaluate method of XPathNavigator. My XML look Like:
<AML> <Item> <sg_percentage>10</sg_percentage> <related_id> <Item> <sg_cost>100<sg_cost> </Item> <related_id> </Item> <Item> <sg_percentage>20</sg_percentage> <related_id> <Item> <sg_cost>500<sg_cost> </Item> <related_id> </Item> <AML>I want SUM(sg_percentage*sg_cost).
最满意答案
当您在参考XSLT时询问它时,我已经为您提供了答案 。 如果没有自定义扩展,则无法使用单个XPath 1.0表达式执行此操作。 您最好的选择是执行以下操作:
decimal sum = 0; foreach (XPathNavigator item in document.CreateNavigator().Select("/AML/Item")) { sum += Convert.ToDecimal(item.Evaluate("sg_percentage * related_id/Item/sg_cost")); }完成后, sum应该具有您正在寻找的值。
对此进行泛化的一种方法是定义一个这样的方法:
public static decimal SumPaths(XmlNode source, string nodePath, string formula) { decimal sum = 0; foreach (XPathNavigator item in source.CreateNavigator().Select(nodePath)) { sum += Convert.ToDecimal(item.Evaluate(formula)); } return sum; }然后你可以这样称呼它:
decimal sum = SumPaths(document, "/AML/Item", "sg_percentage * related_id/Item/sg_cost");I already provided you an answer to this when you asked about it in reference to XSLT. Without custom extensions, there is no way to do this with a single XPath 1.0 expression. Your best bet is to do something like the following:
decimal sum = 0; foreach (XPathNavigator item in document.CreateNavigator().Select("/AML/Item")) { sum += Convert.ToDecimal(item.Evaluate("sg_percentage * related_id/Item/sg_cost")); }When this is finished, sum should have the value you're looking for.
One way to genericize this a bit is to define a method like this:
public static decimal SumPaths(XmlNode source, string nodePath, string formula) { decimal sum = 0; foreach (XPathNavigator item in source.CreateNavigator().Select(nodePath)) { sum += Convert.ToDecimal(item.Evaluate(formula)); } return sum; }And then you can call it like this:
decimal sum = SumPaths(document, "/AML/Item", "sg_percentage * related_id/Item/sg_cost");更多推荐
发布评论