在 XSLT 中按属性值对 XML 节点进行分组 [英] Grouping XML nodes by attribute value in XSLT
问题描述
我对 xslt 转换很陌生,我需要一种转换方面的帮助.我需要按其中一个属性对某种类型的所有节点进行分组,并列出每种属性的父节点.它是一种对文档中某些东西的用法的总结.我将展示简化示例.
输入:
Im quite new to xslt transforms and I need help with one kind of transformation. I need to group all nodes of certain type by one of it atributes and list parents of every kind of attribute. It is a kind of making summary of usage of certain things in the document. The I will present simplified example.
Input:
<root>
<node name="node1">
<somechild child-id="1">
</node>
<node name="node2">
<somechild child-id="2">
</node>
<node name="node3">
<somechild child-id="1">
</node>
<node name="node4">
<somechild child-id="2">
</node>
<node name="node5">
<somechild child-id="3">
</node>
</root>
期望的输出:
<root>
<somechild child-id="1">
<is-child-of>
<node name="node1" />
<node name="node3" />
</is-child-of>
</somechild>
<somechild child-id="2">
<is-child-of>
<node name="node2" />
<node name="node4" />
</is-child-of>
</somechild>
<somechild child-id="3">
<is-child-of>
<node name="node5" />
</is-child-of>
</somechild>
</root>
想法是,如果在许多节点中是相同的元素,则它们具有相同的 child-id.我需要找到每个 .我发现这个问题 XSLT 转换为 xml,按键分组有点相似,但开头有所有作者的声明,而我没有这样的声明,始终只是 .
Idea is that if is the same element in many nodes they have same child-id. I need to find all used by every . I found this question XSLT transformation to xml, grouping by key which is kind of similar but there is a declaration of all authors on the begining and I don't have such, is allways only a child of .
推荐答案
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:key name="k" match="somechild" use="@child-id"/>
<xsl:key name="n" match="node" use="somechild/@child-id"/>
<xsl:template match="root">
<xsl:copy>
<xsl:apply-templates
select="//somechild[generate-id(.) = generate-id(key('k', @child-id))]"/>
</xsl:copy>
</xsl:template>
<xsl:template match="somechild">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<is-child-of>
<xsl:apply-templates select="key('n', @child-id)"/>
</is-child-of>
</xsl:copy>
</xsl:template>
<xsl:template match="node">
<xsl:copy>
<xsl:apply-templates select="@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@*">
<xsl:copy>
<xsl:apply-templates select="@*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
输出:
<root>
<somechild child-id="1">
<is-child-of>
<node name="node1" />
<node name="node3" />
</is-child-of>
</somechild>
<somechild child-id="2">
<is-child-of>
<node name="node2" />
<node name="node4" />
</is-child-of>
</somechild>
<somechild child-id="3">
<is-child-of>
<node name="node5" />
</is-child-of>
</somechild>
</root>
这篇关于在 XSLT 中按属性值对 XML 节点进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!