我知道,一般情况下应避免使用if和choose语句,而应采用模式匹配。然而,在处理排序时,我发现自己必须使用其中之一。无论如何,我可以使用两个语句或一个空的的语句。我想知道哪种方式更有效率。
以下是一些虚拟代码:
XML
感谢您的帮助!
以下是一些虚拟代码:
XML
<?xml version="1.0" encoding="utf-8"?>
<news>
<newsItem id="1">
<title>Title 1</title>
</newsItem>
<newsItem id="2">
<title>Title 2</title>
</newsItem>
<newsItem id="3">
<title></title>
</newsItem>
<newsItem id="4">
<title>Title 4</title>
</newsItem>
<newsItem id="5">
<title>Title 5</title>
</newsItem>
<newsItem id="6">
<title>Title 6</title>
</newsItem>
</news>
XSLT 1
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<ol>
<xsl:apply-templates select="/news/newsItem [string(title)]">
<xsl:sort order="descending" data-type="number" select="@id"/>
</xsl:apply-templates>
</ol>
</xsl:template>
<xsl:template match="newsItem">
<xsl:if test="position() < 5">
<li>
<xsl:value-of select="title"/>
<xsl:if test="position() < 2"> less than two</xsl:if>
<xsl:if test="position() = 3"> equals 3</xsl:if>
</li>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
XSLT 2
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<ol>
<xsl:apply-templates select="/news/newsItem [string(title)]">
<xsl:sort order="descending" data-type="number" select="@id"/>
</xsl:apply-templates>
</ol>
</xsl:template>
<xsl:template match="newsItem">
<xsl:if test="position() < 5">
<li>
<xsl:value-of select="title"/>
<xsl:choose>
<xsl:when test="position() < 2"> less than two</xsl:when>
<xsl:when test="position() = 3"> equals 3</xsl:when>
<xsl:otherwise /> <!-- I know this doesn't need to be here, just included for the sake of readability -->
</xsl:choose>
</li>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
感谢您的帮助!