【问题标题】:Converting flat hierarchy to nested hierarchy in XSLT depth在 XSLT 深度中将平面层次结构转换为嵌套层次结构
【发布时间】:2016-10-27 23:29:59
【问题描述】:

我有一些令人沮丧的扁平 XML,如下所示:

<groups>
    <group id="1" depth="1" />
    <group id="2" depth="2" />
    <group id="3" depth="2" />
    <group id="4" depth="3" />
    <group id="5" depth="2" />
    <group id="6" depth="3" />
</groups>

depth 的最大值似乎是 5

我想把它变成如下所示的 XML:

<groups>
    <group id="1" depth="1">
        <group id="2" depth="2">
        </group>
        <group id="3" depth="2">
            <group id="4" depth="3">
            </group>
        </group>
        <group id="5" depth="2">
            <group id="6" depth="3">
            </group>
        </group>
    </group>
</groups>

认为我需要使用xsl:key,然后为每个parentDepth匹配具有depth = parentDepth + 1以下节点直到 我到达一个带有depth &lt;= parentDepth 的节点,但我不确定如何实现这样的规则。

我想另一种合乎逻辑的方法可能是从“底部”开始并找到具有depth = childDepth - 1 的最新节点,但我不确定这是否可以在 XSLT 中实现。

我也不确定这是否可以针对每个深度递归完成?

我正在使用 XSLT 1.0。

【问题讨论】:

标签: xml xslt recursion xpath hierarchical-data


【解决方案1】:

我想我需要使用 xsl:key 然后为每个 parentDepth 匹配 以下节点具有depth = parentDepth + 1

不,你需要反方向看:让每个孩子找到它的父母,并学习它的唯一id,这样它才能被它调用。

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="child" match="group" use="generate-id(preceding-sibling::group[@depth=current()/@depth - 1][1])" />

<xsl:template match="/groups">
    <xsl:copy>
        <xsl:apply-templates select="group[@depth=1]"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="group">
     <group id="{@id}" depth="{@depth}">
        <xsl:apply-templates select="key('child', generate-id())"/>
    </group>
</xsl:template>

</xsl:stylesheet>

【讨论】:

  • 嗯,这只会给我&lt;groups&gt;&lt;group id="1" depth="1"&gt;&lt;/group&gt;&lt;/groups&gt;。我需要递归吗?
  • 它确实会递归,以防您没有注意到。在这里看到它的工作:xsltransform.net/3NSSEuZ
  • 嗯,MSXML 似乎不喜欢它。也许我需要将 SelectionLanguage 显式切换到 xpath?
  • 恐怕我对此一无所知。
  • 如果深度比较也检查较小的值,源结构中的间隙也会被处理:use="generate-id(preceding-sibling::group[@depth &amp;lt;= ((current()/@depth) - 1)][1])"
猜你喜欢
  • 1970-01-01
  • 2018-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-20
  • 1970-01-01
相关资源
最近更新 更多