xsl:条件检查

时间:2012-08-08 11:14:13

标签: xml xslt xslt-1.0

我有一个输入XML,如下所示

<testing>
<subject ref="yes">
 <firstname>
    tom
 </firstname>
</subject>
<subject ref="no">
 <firstname>
    sam
</firstname>
</subject>
</testing>

我期待我的输出应该是。

如果受试者的答案为是。我会得到名字的价值。否则如果ref(no)我不会获得元素

<testing>
<firstname>
   tom
</firstname>
</testing>

请在这里指导我。

3 个答案:

答案 0 :(得分:2)

这可以通过在身份转换的基础上构建来实现。首先,您需要一个模板来忽略主题元素,其中@ref为“否”

<xsl:template match="subject[@ref='no']" />

对于@ref为“是”的主题元素,您有另一个模板只输出其子元素

<xsl:template match="subject[@ref='yes']">
   <xsl:apply-templates select="node()"/>
</xsl:template>

事实上,如果@ref只能是“是”或“否”,您可以将此模板匹配简化为<xsl:template match="subject">,因为这将匹配所有没有@ref为“否”的元素“

这是完整的XSLT

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

   <xsl:template match="subject[@ref='no']" />

   <xsl:template match="subject">
      <xsl:apply-templates select="node()"/>
   </xsl:template>

   <xsl:template match="@*|node()">
      <xsl:copy>
         <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
   </xsl:template>
</xsl:stylesheet>

当应用于您的示例XML时,输出以下内容

<testing>
<firstname> tom </firstname>
</testing>

答案 1 :(得分:1)

这个短暂的转变:

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

 <xsl:template match="/*">
  <testing><xsl:apply-templates/></testing>
 </xsl:template>

 <xsl:template match="subject[@ref='yes']">
  <xsl:copy-of select="node()"/>
 </xsl:template>
 <xsl:template match="subject"/>
</xsl:stylesheet>

应用于提供的XML文档

<testing>
    <subject ref="yes">
        <firstname>
         tom
     </firstname>
    </subject>
    <subject ref="no">
        <firstname>
         sam
     </firstname>
    </subject>
</testing>

生成想要的正确结果

<testing>
   <firstname>
         tom
     </firstname>
</testing>

答案 2 :(得分:0)

试试这个:

<testing>
  <xsl:if test="testing/subject/@ref = 'yes'">
    <firstname>
      <xsl:value-of select="testing/subject/firstname" />
    </firstname>
  </xsl:if>
</testing>

我希望这应该适用于xslt

相关问题