如何查找特定节点的级别

问题描述 投票:0回答:1

我们是CML:

<menu>
  <item id=1>
    <item id=1.1>
      <item id=1.1.1>
        <item id=1.1.1.1>
        <item id=1.1.1.2>
        <item id=1.1.1.3>
      </item>
    </item>
    <item id=1.2>
      <item id=1.2.1>
        <item id=1.2.1.1>
        <item id=1.2.1.2>
        <item id=1.2.1.3>
      </item>
    </item>
  </item>
</menu>

而我的XSLT:

<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:param name="menuId"/>

<xsl:template match="*">
    <xsl:if test="descendant-or-self::*[@id=$menuId]">
      <xsl:copy>
          <xsl:copy-of select="@*"/>
          <xsl:apply-templates />
      </xsl:copy>
    </xsl:if>
</xsl:template>

<xsl:template match="item">
    <xsl:if test="descendant-or-self::*[@id=$menuId] | 
                                parent::*[@id=$menuId] | 
                                preceding-sibling::*[@id=$menuId] | 
                                following-sibling::*[@id=$menuId] |
                                preceding-sibling::*/child::*[@id=$menuId] | 
                                following-sibling::*/child::*[@id=$menuId]">
    <xsl:copy>
            <xsl:copy-of select="@*"/>
      <xsl:apply-templates select="item"/>
    </xsl:copy>
    </xsl:if>
</xsl:template>


</xsl:stylesheet>

我正在应用一些规则来获取特定节点。没关系。但是现在我需要从所选的menuId获得上面的X(这个数字可以变化)级别

例如。如果X级别数为2且menuId为1.1.2.3,则结果为:

<menu>
    <item id=1.1>
      <item id=1.1.1>
        <item id=1.1.1.1>
        <item id=1.1.1.2>
        <item id=1.1.1.3>
      </item>
    </item>
    <item id=1.2>
    </item>
</menu>

如果X级别编号为1,则结果为:

<menu>
      <item id=1.1.1>
        <item id=1.1.1.1>
        <item id=1.1.1.2>
        <item id=1.1.1.3>
      </item>
</menu>

要获得当前水平,我会使用count(ancestor::*)。但我不知道如何获得节点[@id = $ menuId]级别。我需要在我的IF中加入像count(ancestor::*) >= (count(ancestor::node[@id = $menuId]) - X)这样的东西

谢谢。

xml xslt xmlnode
1个回答
0
投票

我能想到的最有效的方法是将计数参数传递给apply-templates链:

<xsl:variable name="targetDepth" select="count(//item[@id=$menuId]/ancestor::item)" />
<!-- I haven't thought this through in great detail, it might need a +1 -->

<xsl:template match="item">
  <xsl:param name="depth" select="0" />
  ....
  <xsl:if test=".... and ($targetDepth - $depth) &lt;= $numLevels">
    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:apply-templates select="item">
        <xsl:with-param name="depth" select="$depth + 1" />
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:if>
</xsl:template>
© www.soinside.com 2019 - 2024. All rights reserved.