Search code examples
xmlxsltxslt-1.0

How to remove specific XML elements based on value with XSLT


Let's say we have this XML we want to transform:

<?xml version="1.0" encoding="UTF-8"?>
<node>
    <field1>test</field1>
    <field2>/</field2>
    <field3>test2</field3>
    <field4>/<field4>
</node>

I want to transform this using XSLT 1.0 so that the entire structure and all the values are copied, except for elements that have the value "/".

So far I have found this, which I think is not miles away from what I need, but it's not yet working.

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:strip-space elements="*"/>
    <xsl:output indent="yes"/>

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

 <xsl:template match="//text()='/'" />

</xsl:transform>

So the output I expect is this:

<?xml version="1.0" encoding="UTF-8"?>
<node>
    <field1>test</field1>
    <field3>test2</field3>
</node>

When trying this, I am getting an unspecified error (because I'm using free online tools to transform).


Solution

  • //text()='/' is not a valid location path.

    In any case, you want to remove elements, not text nodes - so you should be using something like:

    <xsl:template match="*[.='/']" />