Skip to content

Instantly share code, notes, and snippets.

@akhikhl
Created December 27, 2013 12:06
Show Gist options
  • Save akhikhl/8146185 to your computer and use it in GitHub Desktop.
Save akhikhl/8146185 to your computer and use it in GitHub Desktop.
XSLT transformation b -> bold, i -> italic, text -> normal
import javax.xml.transform.TransformerFactory
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.stream.StreamSource
def input = '''<?xml version="1.0"?>
<p>This is <b>bold text</b>, <i>italic text</i> and normal text</p>
'''
def xslt = '''<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" encoding="UTF-8"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="b">
<c style="bold">
<xsl:apply-templates/>
</c>
</xsl:template>
<xsl:template match="i">
<c style="italic">
<xsl:apply-templates/>
</c>
</xsl:template>
<xsl:template match="text()[not(ancestor::b) and not(ancestor::i)]">
<c style="normal">
<xsl:copy/>
</c>
</xsl:template>
</xsl:stylesheet>'''
def factory = TransformerFactory.newInstance()
def transformer = factory.newTransformer(new StreamSource(new StringReader(xslt)))
transformer.transform(new StreamSource(new StringReader(input)), new StreamResult(System.out))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment