【问题标题】:XSLT: If Node = A then set B=1 Else B=2XSLT:如果 Node = A 则设置 B=1 否则 B=2
【发布时间】:2010-03-19 00:36:05
【问题描述】:

我正在循环查看节点的值。

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 变量设置一次。

【问题讨论】:

    标签: xslt variables loops


    【解决方案1】:

    您提供的代码与 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,所以搜索找不到您的新问题。
    【解决方案2】:

    查看 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 都找到,则执行此操作,否则执行此操作
    猜你喜欢
    • 2011-04-12
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多