对于xslt来说还是新手,请原谅我这是一个基本问题 - 我无法在SO上找到答案,也无法在Google上搜索.
我要做的是返回一组经过筛选的节点,然后在该集合中的前1个或2个项目上进行模板匹配,另一个模板与剩余部分匹配.但是,如果没有<xsl:for-each />
循环,我似乎无法做到这一点(这是非常不受欢迎的,因为我可能匹配3000个节点并且仅以不同方式处理1).
使用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>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
期望的结果:
这个实际上比你想象的要简单.做:
<xsl:template match="newsItem[string(title)][position() < 4]">
Run Code Online (Sandbox Code Playgroud)
并从你的<xsl:apply-templates
选择中删除[string(title)]谓词.
像这样:
<?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>
Run Code Online (Sandbox Code Playgroud)
你在这里有效地做的是[position() < 4]
在你的[string(title)]
过滤器之后应用第二个过滤器(),这导致position()
被应用到过滤列表.