2

我正在寻找显示同级别节点名称的列表,没有重复。

假设我有

<a>
    <b>
        <c />
        <d />
        <d />
    </b>
    <b>
        <e />
        <c />
        <f />
    </b>
</a>

我希望显示 c,d,e,f。我找到了几个解决类似问题的方法,从输出中消除了重复的兄弟姐妹,但我在消除重复的“表亲”时遇到了麻烦。

4

2 回答 2

1

一种可能:

<!-- make all element nodes accessible by their nesting level -->
<xsl:key name="kNodesByLevel" match="*" use="count(ancestor-or-self::*)" />

<xsl:template match="/">
  <!-- select all nodes on one particular level -->
  <xsl:variable name="lvl" select="key('kNodesByLevel', 3)" />

  <!-- step through them... -->
  <xsl:for-each select="$lvl">
    <xsl:sort select="name()" /> 
    <xsl:variable name="name" select="name()" />
    <!-- ... and group them by node name -->
    <xsl:if test="generate-id() = generate-id($lvl[name() = $name][1])"> 
      <xsl:copy-of select="." />
    </xsl:if>
  </xsl:for-each>
</xsl:template>

您提供的 XML 的输出:

<c />
<d />
<e />
<f />
于 2009-07-23T14:25:15.803 回答
0

我会使用 XPath 前同级轴,并检查相同的本地名称。未经测试:

<xsl:template match="c|d|e|f">
    <xsl:if test="local-name(.) != local-name(preceding-sibling::*[1])">
       <xsl:copy-of select="."/>
    </xsl:if>
</xsl:template>

IOW,如果一个元素与它的前一个兄弟同名,它不会被复制。

于 2009-07-23T13:56:17.887 回答