如何不删除空白属性

时间:2014-01-09 16:13:31

标签: xml xslt

我正在生成XML文件并使用XSLT删除任何空白标记或属性。

我最近运行了一个修改,我需要保留一个特定的属性,即使它是空白/ null。

这是我正在使用的XLST:

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

以下是我的XML部分应该是什么样子。

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

我希望保留“noClinicalData”属性,无论其值如何。目前,如果它为null或为空,我的XLST将删除它并离开

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

这是我希望保留的唯一属性。在我的XML中,如果其他属性为空/空,我希望将它们删除。无论如何要修改我的XLST步骤以跳过此属性吗?

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

只需在测试表达式中添加第二个条件:

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

name()(参见reference)函数返回当前节点名称,您可以在表达式中使用逻辑运算符(reference)。

答案 1 :(得分:1)

使用:

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

这样,您的身份转换也会在属性noClinicalData上执行。

在上下文中:

<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>
相关问题