xml - 在 XSLT 中按属性值对 XML 节点进行分组

标签 xml xslt xpath

我对 xslt 转换还很陌生,我需要一种转换方面的帮助。我需要通过其中一个属性对特定类型的所有节点进行分组,并列出每种属性的父节点。它是一种对文档中某些事物的用法进行总结。我将展示简化示例。
输入:

<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>

想法是,如果在许多节点中是相同的元素,则它们具有相同的子 ID。 我需要找到 all 被 every 使用。 我发现了这个问题 XSLT transformation to xml, grouping by key这有点相似,但开头有所有作者的声明,而我没有这样的声明,它始终只是 .

最佳答案

<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>

关于xml - 在 XSLT 中按属性值对 XML 节点进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7243965/

相关文章:

html - 使用 xpath 选择内部带有图像的链接的 href

c# - 如何从 XDocument 中获取 NameTable?

c# - 通用将 xAttribute 转换为 bool

c# - 从xml中分层获取数据

html - 为什么我的 XML 页面不显示转换后的元素?

javascript - 使用 Javascript 修改 XML 元素(在 XSLT 样式表中)

java - 将 JavaBeans 编码为多种格式

java - 弯曲的 vector 绘图未获得全宽度

Java 使用 XSL 将 XML 转换为 HTML

java - 从下到上迭代元素列表的最佳方法是什么?