Mulder
Mulder

Reputation: 39

XSLT to omit elements by position?

My XML looks so:

<A>
 <B>2345</B>
 <B>4444</B>
 <B>1234</B>
</A>

The third element should be extracted that the transformed XML looks so:

<A>
 <B>1234</B>
</A>

I can only use XSLT 1.0. How can I check a certain position of a element?

Upvotes: 3

Views: 422

Answers (2)

Daniel Haley
Daniel Haley

Reputation: 52858

Assuming you have a identity transform to support a "push" model, you can do this by either only applying-templates to the third B...

<xsl:template match="A">
    <xsl:copy>
        <xsl:apply-templates select="B[3]"/>
    </xsl:copy>
</xsl:template>

or matching B elements that are not in the third position and not processing them further...

<xsl:template match="B[not(position()=3)]"/>

Example of the latter: http://xsltfiddle.liberty-development.net/eieFzZN/1

Upvotes: 2

Siebe Jongebloed
Siebe Jongebloed

Reputation: 4869

use:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet  version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  >

  <xsl:template match="A">
    <xsl:copy>
      <xsl:copy-of select="B[3]"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions