加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 07:46:33 所属栏目:百科 来源:网络整理
导读:我对xslt转换很新,我需要一种转换方面的帮助.我需要通过其中一个属性对某些类型的所有节点进行分组,并列出每种属性的父节点.它是对文档中某些内容的使用进行总结.我将介绍简化的例子. 输入: rootnode name="node1" somechild child-id="1"/nodenode name="n
我对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.
我需要找到每个人都使用过的东西.
我发现这个问题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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读