对 xslt 很陌生,所以如果这是一个基本问题,请原谅我 - 我无法在 SO 上或通过 Google 搜索找到答案。
我想要做的是返回一组经过过滤的节点,然后对该组中的前 1 或 2 个项目进行模板匹配,然后另一个模板与其余项目匹配。但是如果没有的话我似乎无法做到这一点<xsl:for-each />
循环(这是非常不可取的,因为我可能匹配 3000 个节点,但仅以不同方式处理 1 个)。
Using position()
不起作用,因为这不受过滤的影响。我尝试对结果集进行排序,但这似乎没有足够早地生效以影响模板匹配。这<xsl:number />
输出正确的数字,但我不能在匹配语句中使用这些数字。
我在下面放置了一些示例代码。我正在使用不合适的position()
下面的方法来说明问题。
提前致谢!
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>
</newsItem>
<newsItem id="5">
<title>Title 5</title>
</newsItem>
</news>
XSL:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<ol>
<xsl:apply-templates select="/news/newsItem [string(title)]" />
</ol>
</xsl:template>
<xsl:template match="newsItem [position() < 4]">
<li>
<xsl:value-of select="title"/>
</li>
</xsl:template>
<xsl:template match="*" />
</xsl:stylesheet>
期望的结果:
- Title 1
- Title 2
- Title 5
这实际上比你想象的要简单。做:
<xsl:template match="newsItem[string(title)][position() < 4]">
并从您的中删除 [string(title)] 谓词<xsl:apply-templates
select.
像这样:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<ol>
<xsl:apply-templates select="/news/newsItem" />
</ol>
</xsl:template>
<xsl:template match="newsItem[string(title)][position() < 4]">
<li><xsl:value-of select="position()" />
<xsl:value-of select="title"/>
</li>
</xsl:template>
<xsl:template match="*" />
</xsl:stylesheet>
您在这里有效做的是应用第二个过滤器([position() < 4]
)在你之后[string(title)]
过滤器,其结果是position()
被应用到过滤列表。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)