带有子串.i的xslt无法获得正确的输出

时间:2015-02-27 16:11:21

标签: xml xslt

我已经返回XSLT获取输出。如果有任何问题,请更正此xslt

<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<item>
<itemSale>
<xsl:if test="itemSale='abed' and itemsearch='bra'">
<xsl:value-of select="substring(itemSale,1,2)">
</xsl:value-of>
</xsl:if>
</itemSale>
</item>
</xsl:template>
</xsl:stylesheet> 

我想要的输出xml是

<?xml version="1.0" encoding="UTF-8"?>
<item>
<itemSale>ab</itemSale>
</item>

输入xml进行测试

<?xml version="1.0"?>
<item>
<itemSale>abed</itemSale>
<itemsearch>bra</itemsearch>
</item>

但我将Output xml改为

<?xml version="1.0" encoding="UTF-8"?>
<item>
<itemSale></itemSale>
</item>

1 个答案:

答案 0 :(得分:2)

您的模板与/(文档根目录)匹配,唯一的子元素是itemitemSaleitemsearch不是根的子项,因此itemSale生成0个节点,itemSale = 'abed'始终为false。

这里有两个主要选项:

  1. 改为匹配文档元素(我推荐这个):
  2. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      <xsl:template match="/*">  <!--  here -->
        <item>
            <itemSale>
                <xsl:if test="itemSale='abed' and itemsearch='bra'">
                    <xsl:value-of select="substring(itemSale, 1, 2)" />
                </xsl:if>
            </itemSale>
        </item>
      </xsl:template>
    </xsl:stylesheet>
    
    1. 使用元素的整个路径:
    2. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:template match="/">
          <item>
              <itemSale>
                  <xsl:if test="item/itemSale='abed' and item/itemsearch='bra'">
                      <xsl:value-of select="substring(item/itemSale, 1, 2)" />
                  </xsl:if>
              </itemSale>
          </item>
        </xsl:template>
      </xsl:stylesheet>