Karen
Karen

Reputation: 35

XSLT When, copy, and delete

This is a simple version of my xml:

<?xml version="1.0" encoding="UTF-8"?>
<level1>

<d1>
    <date type="inclusive">1912-1987</date>
    <date type="bulk">1943-1987</date>
</d1>

<d1>
    <date type="inclusive">1962-1983</date>
    <date type="bulk">1962-1983</date>
</d1>

</level1>

I am trying to write a script to compare the two date type names. If bulk = inclusive, I want it to keep only inclusive and delete bulk. If bulk and inclusive are different, I want the the transform to leave it the way it is.

This is my current transform:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes" encoding="utf-8"/>
<xsl:template match="node() | @*">
    <xsl:copy>
        <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
</xsl:template>
<xsl:variable name="inclusiveDate" select="//date[@type = 'inclusive']/text()"/>
<xsl:variable name="bulkDate" select="//date[@type = 'bulk']/text()"/>
<xsl:template match="//date[@type = 'bulk']">
    <xsl:choose>
        <xsl:when test="$bulkDate = $inclusiveDate">
            <xsl:copy>
                <xsl:apply-templates select="@*"/>
                <xsl:copy-of select="$inclusiveDate[not($bulkDate)]"/>
            </xsl:copy>
        </xsl:when>
    </xsl:choose>
</xsl:template>
</xsl:stylesheet>

And this is what it gives me:

<?xml version="1.0" encoding="utf-8"?>
<level1>
<d1>
    <date type="inclusive">1912-1987</date>
    <date type="bulk"/>
</d1>
<d1>
    <date type="inclusive">1962-1983</date>
    <date type="bulk"/>
</d1>
</level1>

I need it to get rid of

<date type="bulk"/>

completely if it is the same as the inclusive date. And NOT strip out the bulk dates if they are different, leaving it just like this:

<d1>
<date type="inclusive">1912-1987</date>
<date type="bulk">1943-1987</date>
</d1>

I've tried lots of different things at this point.

Upvotes: 1

Views: 36

Answers (1)

Daniel Haley
Daniel Haley

Reputation: 52888

I think first you'd want to match the d1 elements that have matching date elements:

d1[date[@type='bulk'] = date[@type='inclusive']]

Then match the bulk date:

date[@type='bulk']

This can all be combined into a single match:

d1[date[@type='bulk'] = date[@type='inclusive']]/date[@type='bulk'] 

This, along with the identity template, should give you the output you want...

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

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

  <xsl:template 
    match="d1[date[@type='bulk'] = date[@type='inclusive']]/date[@type='bulk']"/>

</xsl:stylesheet>

Working fiddle: http://xsltfiddle.liberty-development.net/94hvTzs

Upvotes: 1

Related Questions