问题描述
我有一个这样的xml代码段:
I have an xml snippet like this:
<root>
<order>
<item>
<item_type>A</item_type>
<item_type>A</item_type>
<item_type>B</item_type>
<item_type>C</item_type>
</item>
</order>
<order>
<item>
<item_type>A</item_type>
<item_type>B</item_type>
<item_type>C</item_type>
<item_type>C</item_type>
</item>
</order>
<order>
<item>
<item_type>C</item_type>
<item_type>C</item_type>
<item_type>B</item_type>
</item>
</order>
</root>
并且我需要按item_type元素对它进行分组,但是在"order"元素范围内,所以我想要的输出是:
and I need to group it by item_type element, but on "order" element scope, so my desired output would be:
<root>
<order>
<item>A</item>
<item>B</item>
<item>C</item>
</order>
<order>
<item>A</item>
<item>B</item>
<item>C</item>
</order>
<order>
<item>B</item>
<item>C</item>
</order>
</root>
我正在使用此xslt 1.0版,但我无法弄清楚.
I'm using this xslt version 1.0, but I can't figure it out.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:key name="groups" match="order/item" use="item_type">
</xsl:key>
<xsl:template match="/">
<xsl:for-each select="//root/order">
<order>
<xsl:for-each select="item[generate-id() = generate-id(key('groups', item_type))]">
<item>
<xsl:value-of select="key('groups', item_type)"/>
</item>
</xsl:for-each>
</order>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
解决方案必须在xslt 1.0中.
Solution have to be in xslt 1.0.
推荐答案
您遇到了很多问题,最重要的是:
You have numerous issues, the most important ones being:
-
您要对
item_type
(而不是item
)进行分组.这意味着您的密钥必须匹配item_type
;
You want to group
item_type
s, notitem
s. That means your key must matchitem_type
;
您想将它们分组在它们的order
中.这意味着您的密钥必须包含唯一的order
标识符.
You want to group them within their order
s. That means your key must include a unique order
identifier.
因此,您的密钥需要定义为:
Therefore your key needs to be defined as:
<xsl:key name="groups" match="item_type" use="concat(., '|', generate-id(ancestor::order))"/>
此外,用于Muenchian分组的语法是错误的.而且您不会输出根元素.
In addition, your syntax for Muenchian grouping is wrong. And you're not outputting a root element.
尝试一下:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:key name="groups" match="item_type" use="concat(., '|', generate-id(ancestor::order))"/>
<xsl:template match="/root">
<root>
<xsl:for-each select="order">
<order>
<xsl:for-each select="item/item_type[generate-id() = generate-id(key('groups', concat(., '|', generate-id(ancestor::order)))[1])]">
<item>
<xsl:value-of select="."/>
</item>
</xsl:for-each>
</order>
</xsl:for-each>
</root>
</xsl:template>
</xsl:stylesheet>
应用于您的输入示例,结果将是:
Applied to your input example, the result will be:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<order>
<item>A</item>
<item>B</item>
<item>C</item>
</order>
<order>
<item>A</item>
<item>B</item>
<item>C</item>
</order>
<order>
<item>C</item>
<item>B</item>
</order>
</root>
这篇关于xslt 1.0嵌套分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!