XSLT:如果节点=A,则设置B=1,否则B=2。

3

我正在循环遍历一个节点的值。

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

我无法弄清楚如何做到这一点。如果我使用的是一种允许变量重新赋值/更改其值的编程语言,那么这很容易。但是,在XSLT中,变量只能设置一次。

2个回答

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>

当这个转换应用于以下 XML 文档时

<c>
  <d/>
</c>

结果为:

   $vA = 2

应用于此文档时:

<c>
  <d>
   <B/>
  </d>
</c>

结果是:

   $vA = 1

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

  <xsl:variable name="vA" select="not(//B) +1"/>

感谢您的回答和示例。我会将其牢记于心以备将来之需。但是我觉得我没有清楚地解释我的问题。已经发布了另一个问题: XSLT:对于每个节点的转换,如果找到A = 2和A = 1则这样做,否则那样做。 - Larry
@Larry,SO搜索找不到你的新问题。 - Dimitre Novatchev

0

请查看xsl:choose、xsl:when和xsl:if。您可以执行

<xsl:if test="A=1">
Set in here
</xsl:if>

<xsl:choose>
    <xsl:when test="A=1">
        <xsl:otherwise>
</xsl:choose>

感谢您的回答和介绍。但我认为我没有清楚地解释我的问题。我已经发布了另一个问题:XSLT:对于每个节点转换,如果找到A = 2和A = 1,则执行此操作,否则执行其他操作。 - Larry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接