xslt-2.0 - 分组和身份转换
问题描述
如何同时应用身份转换和分组
<items>
<user>
<id>8788989</id>
<firstname>test</firstname>
<lastname>user</lastname>
</user>
<info>test xml</info>
<fromdate><fromdate>
<todate></todate>
<item id="123" name="Java">
<price>1</price>
<description></description>
</item>
<item id="123" name="Java and XML">
<price>2</price>
<description></description>
</item>
<item id="234" name="python">
<price>3</price>
<description></description>
</item>
<item id="234" name="scala">
<price>3</price>
<description></description>
</item>
</items>
我想要输出为
<items>
<user>
<id>8788989</id>
<firstname>test</firstname>
<lastname>user</lastname>
</user>
<info>test xml</info>
<fromdate><fromdate>
<todate></todate>
<group>
<item id="123" name="Java">
<price>1</price>
<description></description>
</item>
<item id="123" name="Java and XML">
<price>2</price>
<description></description>
</item>
</group>
<group>
<item id="234" name="python">
<price>3</price>
<description></description>
</item>
<item id="234" name="scala">
<price>3</price>
<description></description>
</item>
</group>
</items>
分组在 item/@id 上完成
解决方案
你可以这样分组:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
version="2.0">
<xsl:output indent="yes"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="items">
<items>
<xsl:apply-templates select="* except item"/>
<xsl:for-each-group select="item" group-by="@id">
<group>
<xsl:apply-templates select="../item[@id = current()/@id]"/>
</group>
</xsl:for-each-group>
</items>
</xsl:template>
</xsl:stylesheet>
更新答案:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
version="2.0">
<xsl:output indent="yes"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="items">
<items>
<xsl:apply-templates select="* except item"/>
<xsl:for-each-group select="item" group-by="@id">
<group>
<xsl:apply-templates select="current-group()"/>
</group>
</xsl:for-each-group>
</items>
</xsl:template>
</xsl:stylesheet>
推荐阅读
- ios - SwiftUI 自定义 List 不能在 ForEach 中使用 Binding
- reactjs - 目标类 [App\\Http\\EnsureFrontendRequestsAreStateful] 不存在
- mysql - 我正在寻找带有将 .sql 文件复制到我的容器的选项的 docker-compose 秘密示例
- javascript - 有什么方法可以结合 transform: scale 对 transform-origin 进行动画处理?
- docker - 无法从部署在同一集群中的我的 golang 应用程序连接到 kubernetes 上的 redis 集群
- for-loop - For Loop in batch 无法使用用户输入作为条件
- javascript - Photoshop 重命名脚本不会遍历文件夹中的图层
- unity3d - 从 IPv4 客户端到仅限 IPv6 的光子服务器的光子连接
- java - 升级到 TLSv1.2 后收到致命警报:handshake_failure
- wordpress - 使用客户用户名/密码对 WooCommerce API 进行身份验证