[xsl] xml fragment to string

Subject: [xsl] xml fragment to string
From: Steven Hentschel <steven.hentschel@xxxxxxxxx>
Date: Wed, 30 Jun 2010 11:04:35 +0100
I'm trying to find a way of converting an xml fragment into a string. The 
reason for wanting to do this is so that the fragment can be stored  in an 
RDBMS as a string and I need to escape any apostrophes for the sql statement.

My method that seems to work with the content that I have is to do the 
following:

<xsl:variable name="xmlAsString" as="xs:string+">
 <xsl:apply-templates>
</xsl:variable>

<!-- template to  turn xml fragment into strings -->
<xsl:template match="*">
  <xsl:value-of select="concat('&lt;', name())"/> 
  <xsl:for-each select="@*">
    <xsl:value-of select="concat(' ', name(), '=&quot;', .,'&quot;')"/>
  </xsl:for-each>
  <xsl:value-of select="'&gt;'"/>
  <xsl:value-of select="text()"/> 
  <xsl:apply-templates select="*"/>
  <xsl:value-of select="concat('&lt;/', name(), '&gt;')"/>
</xsl:template>

then to output the text (using replace() to escape apostrophes

replace(string-join($xmlAsString, ''), '''', '''''')

Are there are other better approaches? Is there a way of dealing with mixed 
content?

Steven Hentschel

Current Thread