Remove elements based on other element's value — XSLT

半腔热情 提交于 2019-11-29 12:05:24

Here is a complete XSLT transformation -- short and simple (no variables, no xsl:if, xsl:choose, xsl:when, xsl:otherwise):

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

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

 <xsl:template match=
 "*[Operation='ABC']/Text | *[Operation='ABC']/Status"/>
</xsl:stylesheet>

When this transformation is applied on the provided XML document:

<Model>
    <Year>1999</Year>
    <Operation>ABC</Operation>
    <Text>Testing</Text>
    <Status>Ok</Status>
</Model>

the wanted, correct result is produced:

<Model>
   <Year>1999</Year>
   <Operation>ABC</Operation>
</Model>

Change your xsl:if as follows:

<xsl:if test="../Operation!='ABC'">

and you can get rid of xsl:variable.

A better pattern in XSLT than using <xsl:if> is to add new templates with match conditions:

<xsl:template match="(Text | Status)[../Operation != 'ABC']"/>

I found this works:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="/Model">
      <xsl:choose>
        <xsl:when test="Operation[text()!='ABC']">
            <xsl:copy>
                <xsl:apply-templates select="node()|@*"/>
            </xsl:copy>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy>
                <xsl:apply-templates select="Year"/>
                <xsl:apply-templates select="Operation"/>
            </xsl:copy>
        </xsl:otherwise>
      </xsl:choose>
  </xsl:template>
</xsl:stylesheet>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!