xslt:选择,如何定义条件

时间:2017-03-10 10:32:26

标签: xml xslt

我正在学习XSLT并编写了一个代码,用于将XML从一种形式转换为另一种形式。我遇到了第一个xsl:when条件的问题。代码未选择条件并跳至xsl:otherwise部分。有人可以帮我辨别我的错误吗?

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">

<FoodList>
<xsl:for-each select="Food/FoodItem">
<xsl:choose>
<xsl:when test="ItemType = 'Fruit'">
This is a fruit
</xsl:when>
<xsl:otherwise>
This is a vegetable
</xsl:otherwise>
</xsl:choose>
<FoodName>
<xsl:value-of select="ItemName"/>
</FoodName>
<FoodQuantity> 
<xsl:value-of select="ItemQuantity"/>
</FoodQuantity>
<xsl:choose>
<xsl:when test="ItemQuantity &gt; 10">
<ShipMessage>
<xsl:text disable-output-escaping="no">can be shipped </xsl:text>
</ShipMessage>
</xsl:when>
<xsl:otherwise>
<ShipMessage>
<xsl:text disable-output-escaping="no">do not ship </xsl:text>
</ShipMessage>
</xsl:otherwise>
</xsl:choose>    
<FoodPrice>
<xsl:value-of select="ItemPrice"/>
</FoodPrice>
</xsl:for-each>
</FoodList>
</xsl:template>
</xsl:stylesheet>

我的输入文件是:

<?xml version="1.0"?>
<Food>
<FoodItem>
<ItemType>  Fruit </ItemType>
<ItemName> Apple  </ItemName>
<ItemQuantity> 5 </ItemQuantity>
<ItemPrice> 300 </ItemPrice>
</FoodItem>
<FoodItem>
<ItemName> Tomato  </ItemName>
<ItemType>  Vegetable </ItemType>
<ItemQuantity> 5 </ItemQuantity>
<ItemPrice> 10 </ItemPrice>
</FoodItem>
<FoodItem>

<ItemName> Mango  </ItemName>
<ItemType>  Fruit </ItemType>
<ItemQuantity> 15 </ItemQuantity>
<ItemPrice> 300 </ItemPrice>
</FoodItem>
</Food>

我得到的输出是:

 <?xml version="1.0" encoding="UTF-8"?><FoodList>
This is a vegetable
<FoodName> Apple  </FoodName><FoodQuantity> 5 </FoodQuantity><ShipMessage>do not ship </ShipMessage><FoodPrice> 300 </FoodPrice>
This is a vegetable
<FoodName> Tomato  </FoodName><FoodQuantity> 5 </FoodQuantity><ShipMessage>do not ship </ShipMessage><FoodPrice> 10 </FoodPrice>
This is a vegetable
<FoodName> Mango  </FoodName><FoodQuantity> 15 </FoodQuantity><ShipMessage>can be shipped </ShipMessage><FoodPrice> 300 </FoodPrice>

2 个答案:

答案 0 :(得分:1)

您的ItemType值不是"Fruit",而是" Fruit "。空白是重要的。如果要匹配忽略空格,请使用

test="normalize-space(ItemType) = "Fruit"

答案 1 :(得分:0)

    <FoodList>
<xsl:for-each select="Food/FoodItem">
<xsl:choose>
<xsl:when test="normalize-space(ItemType) = 'Fruit'">
This is a fruit
</xsl:when>
<xsl:otherwise>
This is a vegetable
</xsl:otherwise>
</xsl:choose>
<FoodName>
<xsl:value-of select="ItemName"/>
</FoodName>
<FoodQuantity> 
<xsl:value-of select="ItemQuantity"/>
</FoodQuantity>
<xsl:choose>
<xsl:when test="ItemQuantity &gt; 10">
<ShipMessage>
<xsl:text disable-output-escaping="no">can be shipped </xsl:text>
</ShipMessage>
</xsl:when>
<xsl:otherwise>
<ShipMessage>
<xsl:text disable-output-escaping="no">do not ship </xsl:text>
</ShipMessage>
</xsl:otherwise>
</xsl:choose>    
<FoodPrice>
<xsl:value-of select="ItemPrice"/>
</FoodPrice>
</xsl:for-each>
</FoodList>
</xsl:template>