Xml – Checking for a duplicate element in the OUTPUT


I've got some XML, for example purposes it looks like this:


I want to transform it with XSLT, but I want to suppress the second f2 element in the output – how do I check inside my template to see if the f2 element already exists in the output when the second f2 element in the source is processed? My XSLT looks something like this at present:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="no" omit-xml-declaration="yes" standalone="no" />
  <xsl:template match="/">
    <xsl:for-each select="./root">
        <xsl:apply-templates />        
  <xsl:template match="*" >
      <xsl:element name="{name(.)}">
        <xsl:value-of select="." />

I need to do some sort of check around the xsl:element in the template I think, but I'm not sure how to interrogate the output document to see if the element is already present.

Edit: Forgot the pre tags, code should be visible now!

Best Solution

It depends how system wide you want to be.

i.e. Are you only concerned with elements that are children of the same parent, or all elements at the same level ('cousins' if you like) or elements anywhere in the document...

In the first situation you could check the preceding-sibling axis to see if any other elements exist with the same name.

<xsl:if test="count(preceding-sibling::node()[name()=name(current())])=0">
  ... do stuff in here.
Related Question