首页 > 解决方案 > xquery 检查 xquery 如何检查布尔变量的值是否为真

问题描述

我正在编写一个 xquery,我必须在其中检查属性的值是否为真。属性/元素定义为布尔值。我尝试了多个选项,但无法获得正确的值,该逻辑适用于其他元素,但不适用于“MainCustomer”,因为它被定义为布尔值。我该如何为此编写xquery?

以下是我的请求示例:

<Maintenance xmlns="*******">
<AccountPersons>
  <APH AccountID="56987" LastFinancialRespSwitch="Y" LastMainCustomerSwitch="Y" LastPersonID="987569" QuickAddSwitch="false"/>
  <APR AccountID="98759" AccountRelationshipType="MIN" BillAddressSource="PER" PersonID="000000" MainCustomer="true"></APR>
  <APR AccountID="123456" AccountRelationshipType="MAIN" BillAddressSource="PERSON" PersonID="123456" MainCustomer="false"></APR>
</AccountPersons>
</Maintenance>

if在 for loop.APR 中使用语句。APR 是一个数组。我只想从 xquery 下面的 MainCustomer="true" 不起作用的那些 APR 中获取 BillAddressSource 的值,它为我提供了所有 APR 的值。

 if (fn:boolean($MaintenanceResponse/ns1:AccountPersons/ns1:APR[$position]/@MainCustomer))
    then
       <acc:data>      
               {if ($MaintenanceResponse/ns1:AccountPersons/ns1:APR[$position]/@BillAddressSource)
                then <acc:addressSource>{fn:data($MaintenanceResponse/ns1:AccountPersons/ns1:APR[$position]/@BillAddressSource)}</acc:addressSource>
                else ()
            }
       </acc:data> 

我尝试的另一个 xquery 是,这给了我语法错误

        if ($MaintenanceResponse/ns1:AccountPersons/ns1:APR[$position]/@MainCustomer='true')
    then
       <acc:data>      
               {if ($MaintenanceResponse/ns1:AccountPersons/ns1:APR[$position]/@BillAddressSource)
                then <acc:addressSource>{fn:data($MaintenanceResponse/ns1:AccountPersons/ns1:APR[$position]/@BillAddressSource)}</acc:addressSource>
                else ()
            }
       </acc:data>  

请帮我找到正确的 if 语句。提前致谢

标签: if-statementbooleanxquery

解决方案


首先,这在一定程度上取决于您的查询/处理器是否支持模式。(是否有“导入模式”声明?)

如果属性存在,则属性的有效布尔值为真,无论其值如何,也无论数据是否经过模式验证。两者都if (@married) ...测试if (boolean(@married)) ...有效的布尔值。

如果要测试属性是否存在并且值为“true”或“1”,请使用强制转换:if (xs:boolean(@married)) ...。无论是否输入数据(通过模式验证),这都将起作用。boolean()请注意获取有效布尔值的函数(有时写成fn:boolean())与xs:boolean()进行数据转换的强制转换或构造函数之间的区别。

如果数据没有类型,您可以使用if (@married = 'true'),但如果数据类型为布尔值,这将失败并出现类型错误。此外,它不会测试所有合法的布尔值(“true”、“1”、“1”等)。

如果您知道数据已通过模式验证键入,则可以使用以下任何一种:

  • if (data(@married)) ...但没有真正的理由更喜欢这个。

  • if (@married = true())- 如果属性存在且为真,则表达式@married = true()返回真,如果不存在或为假,则返回假

  • if (@married eq true())- 如果属性存在且为真,则表达式@married eq true()返回真,如果存在且为假,则返回假,()如果属性不存在,则返回(空序列);()在上下文中返回的效果与if()返回false是一样的。使用“eq”而不是“=”可以带来微小的性能优势。

@married = false()如果您正在测试 false(再次假设类型化数据),则and@married eq false()@married != true()and之间的区别not(@married = true())更加微妙。如果@married不存在,则任何使用=, eq, !=,ne的比较实际上都是错误的,无论另一个操作数是true()还是false()。sonot(@married = true())不等于(@married != true()),也不等于(@married = false())

我可以继续阅读有关此的页面。在我的书(XSLT 2.0 和 XPath 2.0 程序员参考)中,我就是这样做的(参见第 581 到 592 页)。


推荐阅读