我想获得具有最短文本的节点的项目和类型的列表 . 使用xslt / xpath .
我有以下示例xml:
<a>
<b>
<item>short</item>
<item>longest</item>
<item type="x">longest text</item>
<item type="x">short text</item>
<item type="y">text</item>
</b>
</a>
这就是我到目前为止所拥有的
<xsl:template match="ns:item">
<xsl:variable name="type">
<xsl:choose>
<xsl:when test="@type">
<xsl:value-of select="@type" />
</xsl:when>
<xsl:otherwise>default</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:if test="position() = 1">{</xsl:if>
"<xsl:value-of select='$type' />" : "<xsl:value-of select='.' />"
<xsl:if test="position() != last()">,</xsl:if>
<xsl:if test="position() = last()">}</xsl:if>
</xsl:template>
如何从结果中过滤除最短文本之外的所有文本?
输出应该如下所示:
{ "default": "short",
"x" : "short text",
"y" : "text" }
由于我偶尔只使用xslt / xpath而且仅用于非常简单的事情,我希望有人可以帮助我 .
2 回答
我会分组(与Muenchian分组http://www.jenitennison.com/xslt/grouping/index.xml),然后在每组中取最短的项目(只需按长度排序并取第一项):
随着输入
结果是
XSLT 2.0 solution :
when applied on the provided XML document :
the wanted result is produced: