<?xml version="1.0" encoding="UTF-8"?>

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

    <output method="text" indent="yes"/>
    <strip-space elements="*"/>

    <template match="/">
        <apply-templates/>
    </template>

    <template match="*">

        <choose>
            <when test="ancestor::*">
                <text>&#10;</text>
                <for-each select="ancestor::*">
                    <text>  </text>
                </for-each>
            </when>
            <otherwise>
                <text>'</text>
            </otherwise>
        </choose>

        <text>(</text>
        <value-of select="name()"/>
        <if test="@*">
            <text> (attributes</text>
            <apply-templates select="@*"/>
            <text>)</text>
        </if>
        <apply-templates/>
        <text>)</text>
        <if test="position() != last()">
            <text> </text>
        </if>
    </template>

    <template match="@*">
        <text> (</text>
        <value-of select="name()"/>
        <apply-templates/>
        <text>)</text>
    </template>

    <template match="text()" priority="1">
        <text> "</text>
        <call-template name="escape">
            <with-param name="input" select="."/>
        </call-template>
        <text>"</text>
    </template>

    <template name="escape" match="text()">
        <param name="input" select="."/>

        <choose>
            <!-- Escape backslashes -->
            <when test="contains($input, '\')">

                <!-- Handle left side -->
                <call-template name="escape">
                    <with-param name="input" 
                        select="substring-before($input, '\')"/>
                </call-template>

                <text>\\</text>

                <!-- Handle right side -->
                <call-template name="escape">
                    <with-param name="input" 
                        select="substring-after($input, '\')"/>
                </call-template>

            </when>

            <!-- Escape double quotes -->
            <when test="contains($input, '&quot;')">
                <value-of select="substring-before($input, '&quot;')"/>
                <text>\"</text>
                <call-template name="escape">
                    <with-param name="input"
                        select="substring-after($input, '&quot;')"/>
                </call-template>
            </when>

            <otherwise>
                <value-of select="$input"/>
            </otherwise>

        </choose>

    </template>

</xsl:stylesheet>

