Warm tip: This article is reproduced from serverfault.com, please click

How to remove specific XML elements based on value with XSLT

发布于 2020-12-02 17:00:05

I think what I'm trying is pretty simple, but as I am pretty new to XSLT and have been trying/searching for about 4 hours now, I thought I'd ask...

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 "/". Should be easy right? 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. Unspecified because I'm using free online tools to transform. Any help would be greatly appreciated!

Thank you!

Greetings, Nick

Questioner
nikiforos6
Viewed
0
michael.hor257k 2020-12-03 01:20:31

//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="*[.='/']" />