如何使用XSLT对XML元素进行重排、循环与匹配?
当然可以实现!
这在XSLT里属于很典型的分组去重需求,用Muenchian分组技术就能完美解决。我给你拿具体的例子一步步演示,你一看就懂:
示例输入XML
假设你的原始XML结构是这样的:
<root> <listItems> <indexValue>1</indexValue> <description>Apple</description> </listItems> <listItems> <indexValue>2</indexValue> <description>Banana</description> </listItems> <listItems> <indexValue>3</indexValue> <description>Apple</description> </listItems> <listItems> <indexValue>4</indexValue> <description>Orange</description> </listItems> </root>
实现需求的XSLT代码
这段XSLT会帮你完成分组去重,把每个唯一的description作为独立元素,对应的indexValue作为其子元素:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 定义分组键:以description的文本值作为分组依据 --> <xsl:key name="desc-group" match="listItems" use="description"/> <xsl:template match="/root"> <output> <!-- 筛选每个分组的第一个节点,实现description去重 --> <xsl:for-each select="listItems[generate-id() = generate-id(key('desc-group', description)[1])]"> <!-- 用description的值作为元素名称 --> <xsl:element name="{description}"> <!-- 遍历当前分组下的所有listItems,输出对应的indexValue --> <xsl:for-each select="key('desc-group', description)"> <indexValue><xsl:value-of select="indexValue"/></indexValue> </xsl:for-each> </xsl:element> </xsl:for-each> </output> </xsl:template> </xsl:stylesheet>
最终输出XML
运行上面的XSLT后,会得到你想要的结果:
<output> <Apple> <indexValue>1</indexValue> <indexValue>3</indexValue> </Apple> <Banana> <indexValue>2</indexValue> </Banana> <Orange> <indexValue>4</indexValue> </Orange> </output>
可选变体:如果不想用description值当元素名
要是你希望用固定的元素名(比如<descriptionGroup>)来包裹,而不是直接把description值作为元素标签,可以修改XSLT里的元素定义部分:
<!-- 替换原来的<xsl:element name="{description}"> --> <descriptionGroup> <descriptionName><xsl:value-of select="description"/></descriptionName> <xsl:for-each select="key('desc-group', description)"> <indexValue><xsl:value-of select="indexValue"/></indexValue> </xsl:for-each> </descriptionGroup>
对应的输出就会变成:
<output> <descriptionGroup> <descriptionName>Apple</descriptionName> <indexValue>1</indexValue> <indexValue>3</indexValue> </descriptionGroup> <descriptionGroup> <descriptionName>Banana</descriptionName> <indexValue>2</indexValue> </descriptionGroup> <descriptionGroup> <descriptionName>Orange</descriptionName> <indexValue>4</indexValue> </descriptionGroup> </output>
内容的提问来源于stack exchange,提问作者Sharkie563
相关产品推荐
相关产品推荐

