根据XPATH条件返回一个字符串值

Siv*_*n L 14 xpath

如果我有以下XML,如何指定xpath以根据条件返回字符串.例如这里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>
Run Code Online (Sandbox Code Playgroud)

Dim*_*hev 20

I. XPath 2.0解决方案(如果您可以访问XPath 2.0引擎,建议使用)

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

   if(//b[@id=23]) 
     then 'Profit' 
     else 'Loss'
Run Code Online (Sandbox Code Playgroud)

II.XPath 1.0解决方案:

使用:

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

使用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>
Run Code Online (Sandbox Code Playgroud)

当应用于提供的XML文档时(更正为使其格式良好):

<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>
Run Code Online (Sandbox Code Playgroud)

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

Profit
Run Code Online (Sandbox Code Playgroud)

当我们替换XML文档时:

<b id="23"/>
Run Code Online (Sandbox Code Playgroud)

:

<b id="24"/>
Run Code Online (Sandbox Code Playgroud)

再次产生正确的结果:

Loss
Run Code Online (Sandbox Code Playgroud)

说明:

我们使用以下事实:

substring($someString, $N)
Run Code Online (Sandbox Code Playgroud)

是所有人的空字符串$N > string-length($someString).

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

最后:

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

number(false())0定义.

因此:

1 div $someCondition

1什么时候的$someConditiontrue()

Infinity什么时候$someConditionfalse()

因此,由此得出,如果我们要生产$stringX的时候$Condtrue()和生产$stringY的时候$Condfalse(),表达的方式之一是:

concat(substring($stringX, 1 div $cond),
       substring($stringY, 1 div not($cond)),
      )
Run Code Online (Sandbox Code Playgroud)

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

  • +1 Dimitre 你总是提供出色的解释,尤其是涉及 XPath 的问题。我是经验之谈:) (2认同)