简体   繁体   中英

How to remove xml elements/attributes based on condition in xslt

I am struggling with some basic XSLT. I would like to remove an element from some XML depending on whether it has not got a certain attribute(In this case PriorValue). In below exaple if value of "apple" not "good" remove element "same1". If value of "banana" not "other", remove element "same2"

The XML Looks like this The XML is not limited to only the below sections, it has a lot of other sections and the same logic is applied to them as well.

<doc>... 
    <Element name="same1">foo</Element>
    <Element name="apple">cat</Element>
     <Element name="banana">dog</Element>
    <Element name="same2">baz</Element>
    <Element name="same3">foobar</Element>
</doc>

output xml should be like below

<doc>
    <Element name="apple">cat</Element>
     <Element name="banana">dog</Element>
    <Element name="same3">foobar</Element>
</doc>

You can use the following solution in all XSLT versions(1.0,2.0,3.0):

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

    <!-- identity template -->
    <xsl:template match="node()|@*">
      <xsl:copy>
        <xsl:apply-templates select="node()|@*" />
      </xsl:copy>
    </xsl:template>      
    
    <!-- Removal templates matching the 'same?' elements -->
    <xsl:template match="Element[@name='same1'][../Element[@name!='apple'] != 'good']" />
    <xsl:template match="Element[@name='same2'][../Element[@name!='banana'] != 'other']" />
            
</xsl:stylesheet>

The identity template (which can be replaced by <xsl:mode on-no-match="shallow-copy"/> in XSLT-3.0) copies all nodes from the input stream to the output stream. This output is restricted by the empty removal templates - which implement the logic you specified in your question. They match the same? elements and ignore them.

The rest are helper instructions: the xsl:strip-space removes the space between elements and the xsl:output sets some output parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM