XSLT:如果Node = A,则设置B = 1,否则B = 2

Lar*_*rry 3 xslt variables loops

我通过查看节点的值来循环.

If Node = B, then B has one of two possible meanings. 
  --If Node = A has been previously found in the file, then the value for A
    should be sent as 1.
  --If Node = A has NOT been found in the file, the the value for A should 
    be sent as 2.

where file is the xml source to be transformed
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何做到这一点.如果我使用的编程语言允许变量重新分配/更改其值,则很容易.但是,用XSLT变量设置一次.

Dim*_*hev 10

您提供的代码与XSLT完全无关.在问这些问题之前,请阅读一本关于XSLT的好书.

以下是所知道的问题意义的众所周知的方式:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:template match="/">
   <xsl:variable name="vA">
     <xsl:choose>
      <xsl:when test="//B">1</xsl:when>
      <xsl:otherwise>2</xsl:otherwise>
     </xsl:choose>
   </xsl:variable>

   $vA = <xsl:value-of select="$vA"/>
 </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

将此转换应用于以下XML文档时:

<c>
  <d/>
</c>
Run Code Online (Sandbox Code Playgroud)

结果是:

   $vA = 2
Run Code Online (Sandbox Code Playgroud)

应用于此文档时:

<c>
  <d>
   <B/>
  </d>
</c>
Run Code Online (Sandbox Code Playgroud)

结果是:

   $vA = 1
Run Code Online (Sandbox Code Playgroud)

有一种更短的方法可以获得相同的结果:

  <xsl:variable name="vA" select="not(//B) +1"/>
Run Code Online (Sandbox Code Playgroud)