nrg
nrg

Reputation: 35

Get parent element where child elements with specific values do not exist

Using XLST 1.0 I need to retrieve the aa element where it doesn't have a bb element with 'Filter me out' or 'And filter me out too'.

<data>
    <aa>
        <bb>Filter me out</bb>
        <bb>Some information</bb>
    </aa>
    <aa>
        <bb>And filter me out too</bb>
        <bb>Some more information</bb>
    </aa>
    <aa>
        <bb>But, I need this information</bb>
        <bb>And I need this information</bb>
    </aa>
</data>

Once I have the correct aa element I will output each of its bb elements like so:

<notes>
    <note>But, I need this information</note>
    <note>And I need this information</note>
</notes>

Many thanks.

Upvotes: 0

Views: 846

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122384

A standard approach to this sort of thing is to use templates

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <!-- copy everything as-is from input to output unless I say otherwise -->
  <xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()" /></xsl:copy>
  </xsl:template>

  <!-- rename aa to notes -->
  <xsl:template match="aa">
    <notes><xsl:apply-templates select="@*|node()" /></notes>
  </xsl:template>

  <!-- and bb to note -->
  <xsl:template match="bb">
    <note><xsl:apply-templates select="@*|node()" /></note>
  </xsl:template>

  <!-- and filter out certain aa elements -->
  <xsl:template match="aa[bb = 'Filter me out']" />
  <xsl:template match="aa[bb = 'And filter me out too']" />
</xsl:stylesheet>

Those final two templates match the specific aa elements you don't want and then do nothing. Any aa elements that don't match the specific filtering templates will match the less-specific <xsl:template match="aa"> and be renamed to notes.

Anything for which there is no specific template will be caught by the first "identity" template and copied to the output unchanged. This includes the parent element that wraps around all the aa elements (which you haven't provided in your example but it must exist or the input wouldn't be well-formed XML).

Upvotes: 2

Related Questions