[SOLVED] How to remove hyphens from all the xml document with xslt 1.0

Issue

Im really new with XSLT and I want to remove all the hyphens in my XML, whether it is in the attribute value or in text, I have this XML:

<?xml version="1.0" encoding="UTF-8"?>
<SECTION name="-001">
    <THINGS>
        <THING evaluationZ="-29" evaluationY="226" action="-MOVE" name="-XYZ">
            <CT>
                <work task="1">-ALL </work>
                <work task="2">-HIGH</work>
                <work task="3">-FAST</work>
                <work task="4">DET</work>
                <work task="5">-COMPLETE</work>
                <work task="6">-FINISH</work>
            </CT>
            <VAC>
                <days amount="0"/>
                <days amount="2"/>
            </VAC>
        </THING>
    <THINGS>
</SECTION>

And I want this at the output, exactly the same but without any hyphen :

<?xml version="1.0" encoding="UTF-8"?>
<SECTION name="001">
    <THINGS>
        <THING evaluationZ="29" evaluationY="226" action="MOVE" name="XYZ">
            <CT>
                <work task="1">ALL </work>
                <work task="2">HIGH</work>
                <work task="3">FAST</work>
                <work task="4">DET</work>
                <work task="5">COMPLETE</work>
                <work task="6">FINISH</work>
            </CT>
            <VAC>
                <days amount="0"/>
                <days amount="2"/>
            </VAC>
        </THING>
    <THINGS>
</SECTION>

I have this XSLT, but its not working

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

    <xsl:template match="@*|node()">
      <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
    </xsl:template>
    
    <xsl:template match="/">
        <xsl:value-of select="translate(.,'- ','')"/>
    </xsl:template>
    
</xsl:stylesheet>

how can I write the XSLT to achieve what is described above?

Solution

The correct answer is:

XSLT 1.0

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

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

<xsl:template match="@*">
    <xsl:attribute name="{name()}">
        <xsl:value-of select="translate(.,'-','')"/>
    </xsl:attribute>
</xsl:template>

<xsl:template match="text()">
    <xsl:value-of select="translate(.,'-','')"/>
</xsl:template>

</xsl:stylesheet>

Note that this will not copy comments or processing instructions.

Answered By – michael.hor257k

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.