Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not remove a blank attribute

Tags:

xml

xslt

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.

like image 208
Upstart Avatar asked May 31 '26 09:05

Upstart


2 Answers

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).

like image 186
Adriano Repetti Avatar answered Jun 04 '26 13:06

Adriano Repetti


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>
like image 42
Mathias Müller Avatar answered Jun 04 '26 13:06

Mathias Müller