Upstart
Upstart

Reputation: 196

How to not remove a blank attribute

I am generating XML files and using XSLT to remove any blank tags or attributes.

I have recently run it a modification where I need to keep a particular attribute, even if it is blank/null.

Here is the XLST I was using:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:strip-space elements="*"/>
  <xsl:output indent="yes" />
  <xsl:template match="@*|node()">
    <xsl:if test=". != ''">
      <xsl:copy>
        <xsl:apply-templates  select="@*|node()"/>
      </xsl:copy>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

Below is what my XML section should look like.

<patientClinical noClinicalData="">
  <orgFacilityCode>000200</orgFacilityCode>
  <orgPatientId>123456</orgPatientId>
</patientClinical>

I wish to keep the "noClinicalData" attribute, regardless of its value. Currently, if it is null or empty, my XLST is removing it and just leaving

<patientClinical>
  <orgFacilityCode>000200</orgFacilityCode>
  <orgPatientId>123456</orgPatientId>
</patientClinical>

This is the only attribute I wish to keep. Elsewhere in my XML, if other attributes are blank/null, I wish for them to be removed. Is there anyway to modify my XLST step to skip this attribute?

Thanks for the help in advance.

Upvotes: 3

Views: 63

Answers (2)

Mathias M&#252;ller
Mathias M&#252;ller

Reputation: 22617

Use:

 <xsl:if test=". != '' or name()='noClinicalData'">

That way, your identity transform is performed on the attribute noClinicalData, too.

In context:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:strip-space elements="*"/>
 <xsl:output indent="yes" />
 <xsl:template match="@*|node()">
  <xsl:if test=". != '' or name()='noClinicalData' ">
  <xsl:copy>
    <xsl:apply-templates  select="@*|node()"/>
  </xsl:copy>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

Upvotes: 1

Adriano Repetti
Adriano Repetti

Reputation: 67080

Just add a second condition in your test expression:

<xsl:if test=". != '' or name() = 'noClinicalData'">
    <xsl:copy>
        <xsl:apply-templates  select="@*|node()"/>
    </xsl:copy>
</xsl:if>

name() (see reference) function returns current node name and you can use logic operators in expressions (reference).

Upvotes: 1

Related Questions