[XSL-LIST Mailing List Archive Home] [By Thread] [By Date]

[xsl] Re: xsl hex conversion


Subject: [xsl] Re: xsl hex conversion
From: Mike Brown <mike@xxxxxxxx>
Date: Sat, 8 Sep 2001 19:52:16 -0600 (MDT)

topper harley wrote:
>          Is there a function that can convert ASCII coded characters to 
> ASCII coded hex data.

The appropriate place to ask this question is xsl-list, not xml-dev.

Using pure XSLT, and assuming you really meant ASCII (characters 32-127),
here is a demonstration of a way to do it:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:output method="xml" indent="yes"/>

  <!-- the next line is all on one line and the before the ! is a space -->
  <xsl:variable name="ascii"> !"#$%&amp;'()*+,-./0123456789:;&lt;=&gt;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~</xsl:variable>
  <xsl:variable name="hex" >0123456789ABCDEF</xsl:variable>

  <xsl:template match="/">

    <xsl:variable name="foo" select="'I have $1,001.'"/>

    <result>
      <string>
        <xsl:value-of select="$foo"/>
      </string>
      <hex>
        <xsl:call-template name="recurse-over-string">
          <xsl:with-param name="str" select="$foo"/>
        </xsl:call-template>
      </hex>
    </result>

  </xsl:template>

  <xsl:template name="recurse-over-string">
    <xsl:param name="str"/>   
    <xsl:if test="$str">
      <xsl:variable name="first-char" select="substring($str,1,1)"/>
      <xsl:variable name="ascii-value" select="string-length(substring-before($ascii,$first-char)) + 32"/>
      <xsl:variable name="hex-digit1" select="substring($hex,floor($ascii-value div 16) + 1,1)"/>
      <xsl:variable name="hex-digit2" select="substring($hex,$ascii-value mod 16 + 1,1)"/>
      <xsl:value-of select="concat($hex-digit1,$hex-digit2)"/>
      <xsl:if test="string-length($str) &gt; 1">
        <xsl:text> </xsl:text>
        <xsl:call-template name="recurse-over-string">
          <xsl:with-param name="str" select="substring($str,2)"/>
        </xsl:call-template>
      </xsl:if>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>


The output is 

<?xml version="1.0" encoding="utf-8"?>
<result>
   <string>I have $1,001.</string>
   <hex>49 20 68 61 76 65 20 24 31 2C 30 30 31 2E</hex>
</result>


 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list



Current Thread
Keywords