如何使用 XSLT 创建不同的值 [英] How to use XSLT to create distinct values
本文介绍了如何使用 XSLT 创建不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的 XML:
<项目><产品><产品>笔记本电脑</产品><product>充电器</product></产品></项目><项目><产品><产品>笔记本电脑</产品><product>耳机</product></产品></项目></物品>
我希望它像这样输出
<预>笔记本电脑充电器耳机我试图使用 distinct-values()
但我想我做错了什么.谁能告诉我如何使用 distinct-values()
实现这一目标?谢谢.
<xsl:for-each select="//products/product/text()"><li><xsl:value-of select="distinct-values(.)"/></xsl:for-each></xsl:模板>
但它给了我这样的输出:
笔记本电脑 <li>充电器</li><li>笔记本电脑></li><li>耳机</li>
解决方案
使用 key
和 generate-id() 的 XSLT 1.0 解决方案代码>函数来获取不同的值:
<xsl:output method="xml" encoding="UTF-8" indent="yes"/><xsl:key name="product" match="/items/item/products/product/text()" use="."/><xsl:template match="/"><xsl:for-each select="/items/item/products/product/text()[generate-id()= generate-id(key('product',.)[1])]"><li><xsl:value-of select="."/></xsl:for-each></xsl:模板></xsl:stylesheet>
I have XML like this:
<items>
<item>
<products>
<product>laptop</product>
<product>charger</product>
</products>
</item>
<item>
<products>
<product>laptop</product>
<product>headphones</product>
</products>
</item>
</items>
I want it to output like
laptop charger headphones
I was trying to use distinct-values()
but I guess i m doing something wrong. Can anyone tell me how to achieve this using distinct-values()
? Thanks.
<xsl:template match="/">
<xsl:for-each select="//products/product/text()">
<li>
<xsl:value-of select="distinct-values(.)"/>
</li>
</xsl:for-each>
</xsl:template>
but its giving me output like this:
<li>laptop</li>
<li>charger</li>
<li>laptop></li>
<li>headphones</li>
解决方案
An XSLT 1.0 solution that uses key
and the generate-id()
function to get distinct values:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8" indent="yes"/>
<xsl:key name="product" match="/items/item/products/product/text()" use="." />
<xsl:template match="/">
<xsl:for-each select="/items/item/products/product/text()[generate-id()
= generate-id(key('product',.)[1])]">
<li>
<xsl:value-of select="."/>
</li>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
这篇关于如何使用 XSLT 创建不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文