Search code examples
xmlxsltremove-if

Removing specific values within a XML element using XSLT?


During my XSL transformation, I would like to delete all the tags with ContextID="de_DE". This means that the following XML:

 <Values>       
 <Value AttributeID="TEST" ContextID="de_DE" QualifierID="de">1234</Value>        
 <Value AttributeID="TEST" ContextID="fr_FR" QualifierID="fr">1234</Value>        
 <Value AttributeID="TEST100" ContextID="de_DE" QualifierID="de">abcd</Value>        
 <Value AttributeID="TEST100" ContextID="fr_FR" QualifierID="fr">abcd</Value>        
 </Values>

Will become:

 <Values>         
 <Value AttributeID="TEST" ContextID="fr_FR" QualifierID="fr">1234</Value>
 <Value AttributeID="TEST100" ContextID="fr_FR" QualifierID="fr">abcd</Value>        
 </Values>

How do I achieve this?

Thanks in advance!


Solution

  • XSLT doesn't have a notion of 'deletion'. You exclude nodes from the input document by matching them and doing nothing with them. XSLT processors do have a notion of specificity, so a more specific template overrides a less-specific one.

    Something like:

    <!-- Matches all Value elements and copies them verbatim -->
    <xsl:template match="Value">
        <xsl:copy/>
    </xsl:template>
    
    <!-- Matches all Value elements whose ContextID is 'de_DE' in preference to the less-specific template, and does nothing -->
    <xsl:template match="Value[@ContextID='de_DE']"/>