Skip to content

Instantly share code, notes, and snippets.

@x-yuri
Last active October 18, 2024 07:36
Show Gist options
  • Save x-yuri/45b86eed64183be97ad5220777e297c1 to your computer and use it in GitHub Desktop.
Save x-yuri/45b86eed64183be97ad5220777e297c1 to your computer and use it in GitHub Desktop.
XSLT: swap 2 elements

XSLT: swap 2 elements

a.xml:

<a>
    <b/>
    <c/>
    <d/>
    <e/>
    <f/>
    <g/>
    <h/>
    <i/>
</a>

a.xslt:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml"/>
    <xsl:template match="a">
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:apply-templates select="*[following-sibling::*[name() = 'd']]"/>
            <xsl:apply-templates select="g"/>
            <xsl:apply-templates select="*[preceding-sibling::*[name() = 'd'] and following-sibling::*[name() = 'g']]"/>
            <xsl:apply-templates select="d"/>
            <xsl:apply-templates select="*[preceding-sibling::*[name() = 'g']]"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
$ xsltproc /tmp/a.xslt /tmp/a.xml
<?xml version="1.0"?>
<a><b/><c/><g/><e/><f/><d/><h/><i/></a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment