这是我的计算表达式函数和calculateMinus函数
declare function local:calculateExpression($expression) as xs:decimal {
let $result :=
if ($expression/uli:times) then
fold-left($expression/uli:times/*/@value, 1,
function($acc, $val) { $acc * ($val) })
else if ($expression/uli:plus) then
sum( for $child in $expression/uli:plus/@value
return local:calculateExpression($child))
else if ($expression/uli:minus) then
local:calculateMinus($expression/uli:minus)
else if ($expression/uli:int) then
xs:decimal($expression/uli:int/@value)
else if ($expression/uli:dec) then
xs:decimal($expression/uli:dec/@value)
else if ($expression instance of xs:decimal) then
xs:decimal($expression/uli:int/@value)
else
0 (: Default value if no recognized operation is found :)
return
if (empty($result)) then 0 else $result
};
declare function local:calculateMinus($minus as element()) as xs:decimal {
let $operands := $minus/*
return
if (count($operands) = 2) then
local:calculateExpression($operands[1]) - local:calculateExpression($operands[2])
else
local:calculateExpression($operands[1]) - sum(for $op in $operands[position() > 1] return local:calculateExpression($op))
};
不幸的是,它将下面给出的表达式计算为 0
<answer-debug>
<questionID QuestionID="Q4"></questionID>
<answerValue>Not Answered</answerValue>
<correctValue>0</correctValue>
<answerType>string</answerType>
<correctValueType>decimal</correctValueType>
<comparisonResult>Not Answered</comparisonResult>
<marks>0</marks>
</answer-debug>
我认为我在这里正确应用了递归。我有什么遗漏的吗? 供您参考,问题xml的结构是
<Question id="Q4" level="1">
<Expression>
<description/>
<plus>
<int value="1"/>
<int value="1"/>
</plus>
</Expression>
<Feedback answerCorrect="t">Well done!</Feedback>
<Feedback answerCorrect="f">Please pay more attention next time.</Feedback>
</Question>
仅通过一个小示例来揭示您的 XML 结构很难知道,但是
$expression/uli:plus/@value
显然是错误的,因为
uni:plus
元素没有 @value
属性。
当你写作时
for $child in $expression/uli:plus/@value
return local:calculateExpression($child)
看起来
calculateExpression
函数并不是为了处理属性节点而设计的。