Remove elements based on other element's value — XSLT

前端 未结 4 1130
旧时难觅i
旧时难觅i 2020-12-20 03:36

I have a style-sheet that I am using to remove certain elements based on the value of an other element. However, it is not working ...

Sample Input XML



        
相关标签:
4条回答
  • 2020-12-20 03:55

    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>
    
    0 讨论(0)
  • 2020-12-20 04:00

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

    <xsl:template match="(Text | Status)[../Operation != 'ABC']"/>
    
    0 讨论(0)
  • 2020-12-20 04:02

    Change your xsl:if as follows:

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

    and you can get rid of xsl:variable.

    0 讨论(0)
  • 2020-12-20 04:07

    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>
    
    0 讨论(0)
提交回复
热议问题