xml - 用 XSLT 中的元素包围匹配的兄弟姐妹
问题描述
如何在 XSLT 中用新元素包围匹配的相邻兄弟?
在这个例子中,要包围的元素是那些匹配的bar[@baz='quux']
:
XML 输入:
<foo>
<bar>X1</bar>
<bar baz="quux">X2</bar>
<bar baz="quux">X3</bar>
<xnorfzt>X4</xnorfzt>
<bar baz="quux">X5</bar>
</foo>
预期的 XML 输出:
<foo>
<bar>X1</bar>
<new>
<bar baz="quux">X2</bar>
<bar baz="quux">X3</bar>
</new>
<xnorfzt>X4</xnorfzt>
<new>
<bar baz="quux">X5</bar>
</new>
</foo>
解决方案
在 XSLT 2.0 中试试这个
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="foo">
<xsl:copy>
<xsl:for-each-group select="*" group-adjacent="@baz='quux'">
<xsl:choose>
<xsl:when test="current-grouping-key()">
<new>
<xsl:apply-templates select="current-group()"/>
</new>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates select="current-group()"/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>
请参阅https://xsltfiddle.liberty-development.net/pNvt6XR上的转换
在 XSLT 1.0 中
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="bar[preceding-sibling::*[1][self::bar][@baz = 'quux']]" priority="1"/>
<xsl:template match="bar[@baz = 'quux']">
<new>
<xsl:call-template name="wrapbar">
<xsl:with-param name="node" select="."/>
</xsl:call-template>
</new>
</xsl:template>
<xsl:template name="wrapbar">
<xsl:param name="node"/>
<xsl:copy-of select="$node"/>
<xsl:if test="$node/following-sibling::*[1][self::bar][@baz = 'quux']">
<xsl:call-template name="wrapbar">
<xsl:with-param name="node" select="$node/following-sibling::*[1]"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
推荐阅读
- python - 从列表中删除元素
- tensorflow - tensorflow:如何使用 tf.nn.leaky_relu 和 alpha 作为 tf.contrib.layers.fully_connected 的activation_fn?
- ios - 无法单击自定义 UICollectionViewCell 内容
- node.js - 使用 multer 发送状态和文件
- tensorflow - Tensorflow - 训练亚当
- c - 什么是形式参数中的默认存储类
- azure - 如何在 VSTS 中部署 azure 函数应用代码和 ARM 模板
- r - 什么是 dplyr rowwise() 的 Plyr 版本
- azure - 如何使用 Terraform 将 VM 添加到 Azure 中的负载均衡器?
- sql - 我不知道如何创建这个 sql 查询