我是XML和XSLT的新手。我已经阅读了一些教程,并制作了一些简单的XSL代码。现在我正在为这种转变而苦苦挣扎,这让我发疯,因为我不知道该如何处理。
我有类似的XML代码:
<navigation >
<item id="1" >
<item id="6" />
<item id="7" >
<item id="18" />
<item id="19" />
</item>
<item id="8" />
<item id="9" />
</item>
<item id="2">
<item id="10" />
<item id="11" />
<item id="12" />
</item>
<item id="3" >
<item id="13" />
<item id="14" >
<item id="20" />
<item id="21" />
</item>
<item id="15" />
</item>
<item id="4" >
<item id="16" />
<item id="17" />
</item>
<item id="5" />
<current id="7" />
</navigation>
我需要选择当前具有相同" ID"的"项目",例如"当前" ID元素,然后检查它具有孩子 - 另一个项目元素。如果有的话,我想将"儿童id"属性显示为嵌套列表,所选项目及其兄弟姐妹" ID"属性作为第一个级别列表。如果没有,我想将选定的项目及其兄弟姐妹" ID"显示为嵌套列表,而Selected项目的父母和父母的兄弟姐妹作为第一个级别列表。
例如,如果当前ID =" 7"输出将是这样的:
- 6
- 7
- 18
- 19
- 8
- 9
,例如,如果当前ID =" 1"输出将是这样:
-1
-6
-7
-8
-9
-2
-3
-4
-5
要通过其ID找到一个项目元素,设置键
是有意义的<xsl:key name="id" match="item" use="@id"/>
比我们可以使用key('id', current/@id)
选择current
元素引用的项目。
至于您的条件,似乎它们基本上描述了相同的映射,仅用于将映射应用于该叶子元素的父元素的叶子元素。
试图用XSLT 3实现它,我想出了
<xsl:key name="id" match="item" use="@id"/>
<xsl:template match="navigation">
<ul>
<xsl:variable name="current-selection" select="key('id', current/@id)"/>
<xsl:variable name="current-id" select="if ($current-selection[item]) then $current-selection/@id else $current-selection/../@id"/>
<xsl:apply-templates select="if ($current-selection[item]) then $current-selection/../item else $current-selection/../../item">
<xsl:with-param name="current-id" select="$current-id" />
</xsl:apply-templates>
</ul>
</xsl:template>
<xsl:template match="item">
<xsl:param name="current-id"/>
<xsl:choose>
<xsl:when test="@id = $current-id">
<li>
<xsl:value-of select="@id"/>
<ul>
<xsl:apply-templates/>
</ul>
</li>
</xsl:when>
<xsl:otherwise>
<li>
<xsl:value-of select="@id"/>
</li>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
完整的示例https://xsltfiddle.liberty-development.net/bfdb2bk/3,https://xssltfiddle.liberty.liberty.liberty-development.net/bfdbkk/2,https:/bfdb2b2bk/2,https://xssltfiddle.liberty.liberty-p.development.net/bfdb2bk/1