Nirbhay_K
Nirbhay_K

Reputation: 3

Dynamically passing XML node attribute based on a condition to other node using XSLT

I have a big XML file wherein there are 2 nodes which are quite similar. Based on a value from the 1st node I need to remove the non-required repetitions of second node.

Example XML:

<ABC>
    <Project>
        <ProjectBaselines>
            <Baseline current="true" ID="01" />
            <Baseline current="false" ID="02" />
            <Baseline current="false" ID="03" />
        </ProjectBaselines>
    </Project>
    <Tasks>
        <Task>
            <Bline ID="01" />
            <Bline ID="02" />
            <Bline ID="03" />
            <Bline ID="04" />
        </Task>
    </Tasks>
</ABC>

XSLT:

<xsl:template match="Baseline[@current !='true']"/>
<xsl:template match="Bline[@ID != *ID of the Baseline node where current=true*]" />

With the first line of XSLT I am able to remove all the <Baseline> nodes where the current is false; however I am not able to find a way to pass the ID value from <Baseline> tag where current=true.

Upvotes: 0

Views: 167

Answers (1)

Tim C
Tim C

Reputation: 70638

Use a key to look up the Baseline elements by their ID attribute

<xsl:key name="Baselines" match="Baseline" use="@ID" />

Then your template match to ignore Bline elements where the equivalent Baseline is true, is this....

<xsl:template match="Bline[key('Baselines', @ID)/@current = 'true']" />

Try this XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*" />

  <xsl:key name="Baselines" match="Baseline" use="@ID" />

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="Baseline[@current !='true']"/>

  <xsl:template match="Bline[key('Baselines', @ID)/@current = 'true']" />
</xsl:stylesheet>

Upvotes: 1

Related Questions