xslt - XSLT:按两次分组,首先在同一个标签内,然后按 2 个不同的标签
问题描述
我想对以下 XML 进行分组:
<DataSet>
<FirstNode>
<UniqueKey>111</UniqueKey>
<OtherKey>552</OtherKey>
</FirstNode>
<FirstNode>
<UniqueKey>123</UniqueKey>
<OtherKey>552</OtherKey>
</FirstNode>
<FirstNode>
<UniqueKey>154</UniqueKey>
<OtherKey>553</OtherKey>
</FirstNode>
<SecondNode>
<FirstNodeKey>111</FirstNodeKey>
</SecondNode>
<SecondNode>
<FirstNodeKey>123></FirstNodeKey>
</SecondNode>
<SecondNode>
<FirstNodeKey>154></FirstNodeKey>
</SecondNode>
</DataSet>
我想用 XSLT 生成以下 xml:
<DataSet>
<FirstNode>
<UniqueKey>111</UniqueKey>
<OtherKey>552</OtherKey>
</FirstNode>
<FirstNode>
<UniqueKey>123</UniqueKey>
<OtherKey>552</OtherKey>
</FirstNode>
<SecondNode>
<FirstNodeKey>111</FirstNodeKey>
</SecondNode>
<SecondNode>
<FirstNodeKey>123></FirstNodeKey>
</SecondNode>
</DataSet>
<DataSet>
<FirstNode>
<UniqueKey>154</UniqueKey>
<OtherKey>553</OtherKey>
</FirstNode>
<SecondNode>
<FirstNodeKey>154></FirstNodeKey>
</SecondNode>
</DataSet>
基本上我想先按OtherKey对FirstNodes分组,然后按UniqueKey和FirstNodeKey分组。然后每个都应该包含在<DataSet></DataSet>
. 我可以通过使用分组来做到这一点吗?
在此先感谢您的帮助!
解决方案
看来您只是想FirstNode
按子元素对元素进行分组OtherKey
,然后SecondNode
基于以下内容引用任何元素current-group()/UniqueKey
:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="#all"
version="3.0">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:output method="xml" indent="yes"/>
<xsl:key name="second" match="SecondNode" use="FirstNodeKey"/>
<xsl:template match="DataSet">
<xsl:variable name="ds" select="."/>
<xsl:for-each-group select="FirstNode" group-by="OtherKey">
<xsl:copy select="$ds">
<xsl:copy-of select="current-group(), key('second', current-group()/UniqueKey, .)"/>
</xsl:copy>
</xsl:for-each-group>
</xsl:template>
</xsl:stylesheet>
那就是 XSLT 3 与 Saxon 9.8(例如https://xsltfiddle.liberty-development.net/3NzcBtw)或 Altova 2018 一起使用,对于 XSLT 2,您可以拼出
<xsl:copy select="$ds">
<xsl:copy-of select="current-group(), key('second', current-group()/UniqueKey, .)"/>
</xsl:copy>
作为
<DataSet>
<xsl:copy-of select="current-group(), key('second', current-group()/UniqueKey, $ds)"/>
</DataSet>
当然,如果还有其他节点要处理,则将xsl:mode
声明替换为标识模板。
推荐阅读
- azure - Azure AD:id_token 作为不记名令牌
- java - 如何使用 ByteBuffer 进行短到 byte[] 的转换?
- powershell - 设置文化的远程执行
- python - 将所有重复行的列更改为相同的值
- python - 使用 Cuda 在 Python 中使用 numba 在 GPU 上创建数组
- linux - 如何检测 Helgrind(valgrind) 是否给出任何错误
- qt - 使用“color mod”绘制 QPixmap 的最佳方法
- c - c 中的 fgets() 根本不读句子?
- javascript - 如果有新值时如何提醒
在 javascript 中超过 5000
- python - 作业不断失败并出现神秘的错误消息:“org.xerial.snappy.SnappyIOException: [EMPTY_INPUT] 无法解压缩空流” - 如何调试?