首页 文章

xslt - 选择id属性等于id其他属性的元素

提问于
浏览
0

我是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”的“item”,如“current”id元素,然后检查它是否有子项 - 另一个项元素 . 如果有,我想将子“id”属性显示为嵌套列表,并将所选项及其兄弟“id”属性显示为第一级列表 . 如果没有,我想将所选项目及其兄弟姐妹“id”显示为嵌套列表,并将所选项目的父级和父级兄弟姐妹显示为第一级列表 .

例如,如果当前id =“7”输出将是这样的:

- 6
- 7
  - 18
  - 19
- 8
- 9

例如,如果当前id =“1”输出将是这样的:

-1
  -6
  -7
  -8
  -9
-2
-3
-4
-5

1 回答

  • 0

    要按其ID查找item元素,设置密钥是有意义的

    <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/3https://xsltfiddle.liberty-development.net/bFDb2BK/2https://xsltfiddle.liberty-development.net/bFDb2BK/1各种输入的完整示例

相关问题