Home > Back-end >  How to remove specific parts of XML string with XSL
How to remove specific parts of XML string with XSL

Time:06-23

I have following XML document:

    <mail>
        <body> Dear XY,
here are some random information as a placeholder.
==========================================
Fruit_Type: apple
Vagetable_Amount: potato
Animal_Counter: two dogs
==========================================

        </body>
    </mail>

And I need to shorten the body string to this form:

    <mail>
        <body>
            Fruit_Type: apple
            Vagetable_Amount: potato
            Animal_Counter: two dogs
        </body>
    </mail>

Do you have any ideas how to do this?

CodePudding user response:

You could try something like:

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="*"/>

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

<xsl:template match="body">
    <xsl:copy>
        <xsl:value-of select="substring-before(substring-after(., '=====&#10;'), '&#10;=====')"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Added:

To indent the result by a tab, you could do:

<xsl:template match="body">
    <xsl:copy>
        <xsl:for-each select="tokenize(substring-before(substring-after(., '=====&#10;'), '&#10;====='), '&#10;')">
            <xsl:text>&#10;&#9;</xsl:text>
            <xsl:value-of select="." />
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

provided your processor supports XSLT 2.0.

  • Related