根据 XPATH 条件返回字符串值 [英] Return a string value based on XPATH condition

查看:27
本文介绍了根据 XPATH 条件返回字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下 XML,如何指定 xpath 以根据条件返回字符串.例如这里 if//b[@id=23] then "Profit" else "Loss"

If I have the below XML, how to specify a xpath to return a string based on a condition. For example here if //b[@id=23] then "Profit" else "Loss"

<a>
  <b id="23"/>
  <c></c>
  <d></d>
  <e>
    <f id="23">
       <i>123</i>
       <j>234</j>
    <f>
    <f id="24">
       <i>345</i>
       <j>456</j>
    <f>
    <f id="25">
       <i>678</i>
       <j>567</j>
    <f>
  </e>
</a>

推荐答案

I.XPath 2.0 解决方案(推荐使用 XPath 2.0 引擎)

I. XPath 2.0 solution (recommended if you have access to an XPath 2.0 engine)

   (: XPath 2.0 has if ... then ... else ... :) 

   if(//b[@id=23]) 
     then 'Profit' 
     else 'Loss'

二.XPath 1.0 解决方案:

使用:

concat(substring('Profit', 1 div boolean(//b[@id=23])),
       substring('Loss', 1 div not(//b[@id=23]))
      )

使用 XSLT 1.0 进行验证:

这种转变:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
  <xsl:value-of select=
   "concat(substring('Profit', 1 div boolean(//b[@id=23])),
           substring('Loss', 1 div not(//b[@id=23]))
          )"/>
 </xsl:template>
</xsl:stylesheet>

应用于提供的 XML 文档时(已更正以使其格式正确):

when applied on the provided XML document (corrected to make it well-formed):

<a>
    <b id="23"/>
    <c></c>
    <d></d>
    <e>
        <f id="23">
            <i>123</i>
            <j>234</j>
        </f>
        <f id="24">
            <i>345</i>
            <j>456</j>
        </f>
        <f id="25">
            <i>678</i>
            <j>567</j>
        </f>
    </e>
</a>

产生想要的、正确的结果:

Profit

当我们在 XML 文档中替换时:

<b id="23"/>

:

<b id="24"/>

再次产生正确的结果:

Loss

说明:

我们使用以下事实:

substring($someString, $N)

是所有 $N > 的空字符串字符串长度($someString).

此外,数字 Infinity 是唯一大于任何字符串的字符串长度的数字.

Also, the number Infinity is the only number greater than the string-length of any string.

最后:

number(true()) 根据定义是 1

number(false()) 根据定义是 0.

因此:

1 div $someCondition

1 正好当 $someConditiontrue()

is 1 exactly when the $someCondition is true()

并且是 Infinity,而 $someConditionfalse()

因此,如果我们想在 $Condtrue() 时产生 $stringX 并产生$stringY$Condfalse() 时,一种表达方式是:

Thus it follows from this that if we want to produce $stringX when $Cond is true() and to produce $stringY when $Cond is false(), one way to express this is by:

concat(substring($stringX, 1 div $cond),
       substring($stringY, 1 div not($cond)),
      )

在上面的表达式中,concat() 函数的两个参数中的一个是非空的.

In the above expression exactly one of the two arguments of the concat() function is non-empty.

这篇关于根据 XPATH 条件返回字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆