gpt4 book ai didi

xml - xslt 匹配筛选结果集的前 x 项

转载 作者:数据小太阳 更新时间:2023-10-29 02:21:17 24 4
gpt4 key购买 nike

对 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>

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() &lt; 4]">
<li>
<xsl:value-of select="title"/>
</li>
</xsl:template>

<xsl:template match="*" />
</xsl:stylesheet>

期望的结果:

  1. 标题 1
  2. 标题 2
  3. 标题 5

最佳答案

这个实际上比您想象的要简单。做:

 <xsl:template match="newsItem[string(title)][position() &lt; 4]">

然后从 <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() &lt; 4]">
<li><xsl:value-of select="position()" />
<xsl:value-of select="title"/>
</li>
</xsl:template>

<xsl:template match="*" />
</xsl:stylesheet>

你在这里有效地做的是在你的 [position() &lt; 4] 之后应用第二个过滤器 ( [string(title)] )过滤器,结果为 position()被应用于过滤列表。

关于xml - xslt 匹配筛选结果集的前 x 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5067791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com