Thursday, April 21, 2011

Matching only one of many unknown nodes with xpath

Hello.

Im trying to match only one of each node with a generic match. Can this be done generic at all? I would have prefered to just match one of each node with the same local-name()

<xsl:variable name="xmltree">
  <node />
  <anothernode />
  <node />
  <anothernode />
  <unknown />
  <anothernode />
  <node />
  <unknown />
</xsl:variable>

<xsl:template match="/">
  <xsl:apply-templates select="$xmltree/*" mode="MODULE"/>
</xsl:template>

<xsl:template match="*" mode="MODULE" /> <!-- EMPTY MATCH -->

<xsl:template match="node[1]|anothernode[1]|unknown[1]" mode="MODULE">
  <!-- Do something -->
</xsl:template>
From stackoverflow
  • This is a grouping question and in XSLT 1.0 the most efficient way to do grouping is the Muenchian method.

    If the number of elements is not too-big, the following short code might be sufficient:

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
     <xsl:strip-space elements="*"/>
    
        <xsl:template match="/*/*">
         <xsl:copy-of select=
          "self::*[not(preceding-sibling::*
                          [name() = name(current())]
                       )
                   ]"/>
        </xsl:template>
    </xsl:stylesheet>
    

    When this transformation is applied on the following source XML document:

    <t>
        <node />
        <anothernode />
        <node />
        <anothernode />
        <unknown />
        <anothernode />
        <node />
        <unknown />
    </t>
    

    The wanted result is produced:

    <node/>
    <anothernode/>
    <unknown/>
    

    One may study the XPath expressions used in order to understand that this transformation copies really every first occurence of an element with a specific name.

    Sveisvei : Thank you. This will solve it. Thanx Dimitre(the xslt-master).

0 comments:

Post a Comment