Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

James Robertson http://www.r0bertson.co.uk

« Newer Snippets
Older Snippets »
Showing 1-10 of 21 total  RSS 

Using the XSLT function document()

I found an XSLT solution recently using the built-in function document() to include an additional XML document into the current XML document.

Using the file lunch.xml with drink.xml I can show what is available for today's lunch menu.

file: lunch.xml
<food>
  <item name="banana"/>
  <item name="apple"/>
  <item name="custard"/>
  <item name="crisps"/>
</food>  


file: drink.xml
<drinks>
  <drink name="water"/>
  <drink name="orange"/>
  <drink name="lemonade"/>
  <drink name="cream soda"/>
  <drink name="tea"/>
  <drink name="coffee"/>
  <drink name="blackcurrant juice"/>
  <drink name="ginger ale with lime"/>
</drinks>


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

<xsl:template match="food">
<html>
  <head><title>Food menu</title></head>
  <body>
  <h1>To eat</h1>
  <ul>
  <xsl:apply-templates select="item" />
  </ul>
  <h1>To drink</h1>
  <xsl:value-of select="document('drink.xml')/drinks/drink[2]/@name"/>
  </body>
</html>
         
</xsl:template>

<xsl:template match="item">
  <li><xsl:value-of select="@name"/></li>
</xsl:template>

</xsl:stylesheet>



output:
<html><body>
<h1>To eat</h1>
<ul>
<li>banana</li>
<li>apple</li>
<li>custard</li>
<li>crisps</li>
</ul>
<h1>To drink</h1>orange</body></html>

Converting text to SVG

First of all the Ruby code reads the text, splits it into an array and then saves it in XML format.
require 'rexml/document'
include REXML

a = "Open source is a development method for software that harnesses the power of distributed peer 
review and transparency of process. The promise of open source is better quality, higher reliability, 
more flexibility, lower cost, and an end to predatory vendor lock-in.".split(' ') 

doc = Document.new
doc.add_element('text')
oline = Element.new('line')

char_count = 0
a.each do |word|
  
  oword = Element.new('word')
  oword.text = word.to_s
  oword.add_attribute('length',char_count)
  oline << oword 
  char_count += word.length
  
  if char_count > 50
    doc.root << oline
    oline = Element.new('line')
    char_count = 0
  end
end
doc.root << oline
puts char_count
puts doc

Here's a sample of the XML created
<text>
  <line>
    <word length='0'>Open</word><word length='4'>source</word><word length='10'>is</word>
    <word length='12'>a</word><word length='13'>development</word><word length='24'>method</word>
    <word length='30'>for</word><word length='33'>software</word><word length='41'>that</word>
    <word length='45'>harnesses</word>
  </line>
  <line>
    <word length='0'>the</word><word length='3'>power</word>
    <word length='8'>of</word><word length='10'>distributed</word><word length='21'>peer</word>
    <word length='25'>review</word><word length='31'>and</word><word length='34'>transparency</word>
    <word length='46'>of</word><word length='48'>process.</word>
  </line>
  <line>
    <word length='0'>The</word>
    <word length='3'>promise</word><word length='10'>of</word><word length='12'>open</word>
    <word length='16'>source</word><word length='22'>is</word><word length='24'>better</word>
    <word length='30'>quality,</word><word length='38'>higher</word><word length='44'>reliability,</word>
  </line>
  <line>
    <word length='0'>more</word><word length='4'>flexibility,</word><word length='16'>lower</word>
    <word length='21'>cost,</word><word length='26'>and</word><word length='29'>an</word>
    <word length='31'>end</word><word length='34'>to</word><word length='36'>predatory</word>
    <word length='45'>vendor</word>
  </line>
  <line>
    <word length='0'>lock-in.</word>
  </line>
</text>

The XML is then transformed to SVG using the following XSL file
<?xml version="1.0" encoding="UTF-8"?>

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

<xsl:output encoding="UTF-8"
            method="xml"
            indent="yes"/>
            
  <xsl:template match="text">
    <svg xmlns="http://www.w3.org/2000/svg" width="100%"
                  xmlns:xlink="http://www.w3.org/1999/xlink" >
      <g id="sketch" class="sketch">
        <xsl:apply-templates select="line"/>
      </g>
    </svg>
  </xsl:template>
  
  <xsl:template match="line">
    <xsl:variable name="xfactor">12</xsl:variable>
    <xsl:variable name="yfactor">20</xsl:variable>
    <xsl:variable name="pos" select="position()"></xsl:variable>
    <xsl:apply-templates select="word">
      <xsl:with-param name="xfactor" select="$xfactor"></xsl:with-param>
      <xsl:with-param name="y" select="$pos * $yfactor + 10"></xsl:with-param>
    </xsl:apply-templates>
  </xsl:template>

  <xsl:template match="word">
    <xsl:param name="xfactor"/>
    <xsl:param name="y"/>
    <text xmlns="http://www.w3.org/2000/svg" font-size="12pt" x="{@length * $xfactor +10}" y="{$y}" id="t1"><xsl:value-of select="."/></text>
  </xsl:template>
</xsl:stylesheet>

The final SVG output [twitxr.com] shows 5 lines of text with each word as a separate SVG text element.

Passing an XSL param from one template to another

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

<xsl:variable name="xx">
  <html>
  <body>
  <xsl:call-template name="show_title">
    <xsl:with-param name="title" />
  </xsl:call-template>
  </body>
  </html>
</xsl:variable>

<xsl:template name="show_title" match="/">
  <xsl:param name="title" />
  <xsl:for-each select="catalog/cd">
    <p>Title: <xsl:value-of select="$title" /></p>
  </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

source: XSLT <xsl:param> Element [w3schools.com]

Using XSLT to generate SVG

This XSL file is intended to be used as an SVG XSL template file which displays SVG content using Gorg (XSLT back-end processor).
<?xml version="1.0" encoding="UTF-8"?>

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

<xsl:output encoding="UTF-8"
            method="xml"
            indent="yes"/>
            
  <xsl:template match="mainpage">
  <svg xmlns="http://www.w3.org/2000/svg" width="100%"
                xmlns:xlink="http://www.w3.org/1999/xlink" >

    <g>
    <text font-size="12pt" x="50" y="50" id="t2" stroke="olive"><xsl:value-of select="title"/></text>
    </g>

  </svg>
  </xsl:template>
</xsl:stylesheet>


Reference: 'using XSLT to generate SVG' http://snurl.com/24pwo [carto.net]

Format Ruby code in HTML

This code uses the Ruby gem 'syntax' to create an XML file containing the HTML tags around the code, which is then transformed into an HTML file. The working example was first built using coding examples from Howto format ruby code for blogs [wolfman.com] and Formatting Ruby and HTML code for blog posting [blogspot.com]

#!/usr/bin/ruby

#file: ruby2html.rb 

require 'rubygems'
require 'syntax/convertors/html'
require 'projxslt' # <- this is my own class to do an XSLT transform 
require 'rexml/document'
include REXML

class Ruby2Html
  def initialize(rubyfile, htmlfile)
    code = File.read(rubyfile)
    convertor = Syntax::Convertors::HTML.for_syntax "ruby"
    code_html = convertor.convert(code)
    
    tempfile = '../temp/ruby2html.xml'
    xslfile = '../ruby2html/ruby2html.xsl'
    save_file(tempfile, code_html)
    
    px = Projxslt.new(tempfile, xslfile)
    buffer = px.transform()
    save_file(htmlfile, buffer)
    
  end
  
  def save_file(filename, buffer)
    file = File.new(filename, 'w')
    file.puts buffer
    file.close
  end
end

if __FILE__ == $0
  r2h = Ruby2Html.new('ruby2html.rb', '../temp/ruby2html.html')
  puts 'completed'
end

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

  <xsl:output method="html" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
          doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
          encoding="ISO-8859-1"/> 

	<xsl:template match="/">
	<xsl:element name="html">

        <head>
          <title>Sample code</title>
          <link rel="stylesheet" type="text/css" href="ruby2html.css" />
	</head>

	<body>
          <div id="wrap">
          <xsl:apply-templates />
          </div>
	</body> 

	</xsl:element>
	</xsl:template>

	<xsl:template match="pre">
	  <xsl:copy-of select="."/>
	</xsl:template>

</xsl:stylesheet>

Here's the output from the formatted Ruby HTML code [twitxr.com]

Referemce: Syntax Manual [rubyforge.org]

Display a filtered list using XSLT

Following on from the post A simple XSLT example [dzone.com], this code lists all files which have the type 'rb' (equivalent to ls *.rb).

file: dir.xsl
<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      
    <xsl:template match="dir">
    <div id="articles">
      <ul>
      <xsl:apply-templates select="records/file[@type='rb']"/>
      </ul>
    </div>
    </xsl:template>
    
    <xsl:template match="records/file[@type='rb']">
      <li><xsl:value-of select="."/></li>
    </xsl:template>
    
</xsl:stylesheet>

output:
<div id='articles'>
  <ul>
    <li>projxmlhelper.rb</li>
    <li>feedpopulated.rb</li>
    <li>squrl_handler.rb</li>
    <li>password_handler.rb</li>
    <li>category.rb</li>
    <li>gwd.rb</li>
  </ul>
</div>



*update 11:58am 26-Feb*
Here's a filter I will be using in my projects

<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      
    <xsl:template match="dir">
    <div id="articles">
      <ul>
      <xsl:apply-templates select="records/file"/>
      </ul>
    </div>
    </xsl:template>
    
    <xsl:template match="records/file">
      <xsl:if test="@type=$type">
        <li><xsl:value-of select="."/></li>
      </xsl:if>
    </xsl:template>
    
</xsl:stylesheet>

A simple XSLT example

Produce a list of filenames using XML and XSLT

file: dir.xsl
<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      
    <xsl:template match="dir">
    <div id="articles">
      <ul>
      <xsl:apply-templates select="records/file"/>
      </ul>
    </div>
    </xsl:template>
    
    <xsl:template match="records/file">
      <li><xsl:value-of select="."/></li>
    </xsl:template>
    
</xsl:stylesheet>


file: dir.xml
<dir>
  <summary>
    <directory>./</directory>
  </summary>
  <records>
    <file type='xml'>mjournal.xml</file>
    <file type='rb'>projxmlhelper.rb</file>
    <file type='rb'>feedpopulated.rb</file>
    <file type='rb'>squrl_handler.rb</file>
    <file type='cgi'>snurl.cgi</file>
    <file type='cgi'>dynalert.cgi</file>
    <file type='rb'>password_handler.rb</file>
    <file type='rb'>category.rb</file>
    <file type='rb'>gwd.rb</file>
    <file type='cgi'>new-journal-entry.cgi</file>
  </records>
</dir>


then transforming the XML with the command 'xsltproc dir.xsl dir.xml' produces the following:
output:
<div id='articles'>
  <ul>
    <li>mjournal.xml</li>
    <li>projxmlhelper.rb</li>
    <li>feedpopulated.rb</li>
    <li>squrl_handler.rb</li>
    <li>snurl.cgi</li>
    <li>dynalert.cgi</li>
    <li>password_handler.rb</li>
    <li>category.rb</li>
    <li>gwd.rb</li>
    <li>new-journal-entry.cgi</li>
  </ul>
</div>

Save a Ruby source text file to XML.

This code will output a text file as an XML file which can later be transformed into an HTML file using a back-end XSLT processor called Gorg.

#!/usr/bin/ruby 

#file: rubytxt2xml.rb

require 'rexml/document'
include REXML

class RubyTxt2XML
  
  def rubytxt2xml(h)
    h[:infilepath] = './' if h[:infilepath].nil?
    h[:outfilepath] = './' if h[:outfilepath].nil?
    h[:xmlfile] = h[:sourcefile][/^(.*)\.\w+$/,1] + '.xml' if h[:xmlfile].nil?
    buffer = File.new(h[:infilepath] + h[:sourcefile],'r').read
    
    doc = Document.new
    doc.add_element('ruby_txt')
    body = Element.new('source')
    body.text = CData.new(buffer)
    doc.root.add_element(body)
    
    file = File.new(h[:outfilepath] + h[:xmlfile],'w')
    file.puts doc
    file.close
    
  end
end

if __FILE__ == $0
  rt2x = RubyTxt2XML.new
  rt2x.rubytxt2xml(:sourcefile  => 'rubytxt2xml.rb')
end

output:
<ruby_txt>
  <source>
    <![CDATA[
      #!/usr/bin/ruby 

      #file: rubytxt2xml.rb

      require 'rexml/document'
      include REXML

      class RubyTxt2XML
        
        def rubytxt2xml(h)
          h[:infilepath] = './' if h[:infilepath].nil?
          h[:outfilepath] = './' if h[:outfilepath].nil?
          h[:xmlfile] = h[:sourcefile][/^(.*)\.\w+$/,1] + '.xml' if h[:xmlfile].nil?
          buffer = File.new(h[:infilepath] + h[:sourcefile],'r').read
          
          doc = Document.new
          doc.add_element('ruby_txt')
          body = Element.new('source')
          body.text = CData.new(buffer)
          doc.root.add_element(body)
          
          file = File.new(h[:outfilepath] + h[:xmlfile],'w')
          file.puts doc
          file.close
          
        end
      end

      if __FILE__ == $0
        rt2x = RubyTxt2XML.new
        rt2x.rubytxt2xml(:sourcefile  => 'rubytxt2xml.rb')
      end
    ]]>
  </source>
</ruby_txt>

Using XSLT to convert a value to upper or lowercase

This code was copied from XSLT Case Conversion Solution [topxml.com]

Firstly lets place all the letters of the alphabet, lower case and upper case in variables.
<xsl:variable name="lcletters">abcdefghijklmnopqrstuvwxyz</xsl:variable>
<xsl:variable name="ucletters">ABCDEFGHIJKLMNOPQRSTUVWXYZ</xsl:variable>

To then convert our data to upper case we use the translate method, which replaces all the lower case characters with upper case.
<xsl:value-of select="translate($toconvert,$lcletters,$ucletters)"/>

Lower Case Transformation

The lower case transformation is basically the same:
<xsl:value-of select="translate($toconvert,$ucletters,$lcletters)"/>

Converting XHTML to XML

Based on the code from 'Convert from HTML to XML with HTML Tidy', this code will read an xhtml file and extract text to gallery.xml as instructed by xhtml2xml.xml

#!/usr/bin/ruby
  
  require 'tidy'
  require 'projxslt'
  
  FILE_PATH = "../"
  
  class Xhtml2Xml
    def convert()
      project = 'xhtml2xml'
      filein = 'xhtml2xml.xml'
      filehtml = 'gallery.html'
      filexml = 'gallery_xhtml.xml'
      xslfile_temp = 'gallery.xsl'
      xslfile = 'xhtml2xml.xsl'
      fileout = 'gallery.xml'
      tidy_config = 'tidy.txt'
      
      project_path = FILE_PATH + project + '/'
      tidy_config_path = project_path + tidy_config
      filein_path = project_path + filein
      filehtml_path = project_path + filehtml
      filexml_path = project_path + filexml
      xslfile_temp_path = project_path + xslfile_temp
      xslfile_path = project_path + xslfile
      fileout_path = project_path + fileout
      
      Tidy.path = '/usr/lib/libtidy.so'

      file = File.new(filehtml_path,'r')
      buffer = file.read
      xml = Tidy.open(:show_warnings=>true) do |tidy|
        tidy.options.output_xml = true
        tidy.load_config(tidy_config_path)
        puts tidy.options.show_warnings
        xml = tidy.clean(buffer)
        puts tidy.errors
        puts tidy.diagnostics
        xml
      end
      
      #strip out the html document type declaration and save the file
      html_declaration = xml[/<!([^>]*>){2}/]
      save_file(filexml_path, xml.gsub(html_declaration,'<html>'))    
      transform(filein_path, xslfile_path, xslfile_temp_path)
      transform(filexml_path, xslfile_temp_path, fileout_path)
      
    end
    
    def transform(xml_filepath, xsl_filepath, save_filepath)
      pxsl = Projxslt.new(xml_filepath, xsl_filepath)
      outfile = pxsl.transform
      save_file(save_filepath, outfile)
    end
    
    def save_file(filepath, buffer)
      file = File.new(filepath,'w') 
      file.puts buffer
      file.close
    end    
  end
  
  if __FILE__ == $0
    h2x = Xhtml2Xml.new()
    h2x.convert()
  end

file: xhtml2xml.xml
<root element="gallery">
  <summary>
    <field element="title" xpath="head/title"/>
  </summary>
  <record xpath="body/center/table/tr/td" element="photo">
    <field xpath="font/br[3]/preceding-sibling::text()[1]" element="title"></field>
    <field xpath="/html/body/table/tr/td[2]/font/br[3]/preceding-sibling::text()[1]" element="date"></field>
    <field xpath="font/br[1]/preceding-sibling::text()[1]" element="image"></field>
    <field xpath="font/br[2]/preceding-sibling::text()[1]" element="description"></field>
  </record>
</root>

file:xhtml2xml.xsl (transforms the file xhtml2xml.xml to file gallery.xsl)
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="root">
    <xsl:variable name="colon"><xsl:text>:</xsl:text></xsl:variable>
    
    <xsl:element name="xsl:stylesheet">
      <xsl:attribute name="xmlns{$colon}xsl">
        <xsl:text>http://www.w3.org/1999/XSL/Transform</xsl:text>
      </xsl:attribute>
      <xsl:attribute name="version">
        <xsl:text>1.0</xsl:text>
      </xsl:attribute><xsl:text>
      </xsl:text>

<xsl:element name="xsl:output">
  <xsl:attribute name="method">
    <xsl:text>xml</xsl:text>
  </xsl:attribute>
  <xsl:attribute name="indent">
    <xsl:text>yes</xsl:text>
  </xsl:attribute>
</xsl:element><xsl:text>

</xsl:text>

<xsl:element name="xsl:template">
      <xsl:attribute name="match">
        <xsl:text>html</xsl:text>
      </xsl:attribute><xsl:text>
</xsl:text>
      <xsl:element name="{@element}">
      <xsl:apply-templates select="summary"/>

      <xsl:element name="xsl{$colon}for-each">
        <xsl:attribute name="select">
          <xsl:value-of select="record/@xpath"/>
        </xsl:attribute><xsl:text>
    </xsl:text>              

  <xsl:for-each select="record/field">
    <xsl:element name="xsl:variable">
      <xsl:attribute name="name">
        <xsl:value-of select="@element"/>
      </xsl:attribute>
      <xsl:attribute name="select">
        <xsl:value-of select="@xpath"/>
      </xsl:attribute>
    </xsl:element><xsl:text>
    </xsl:text>
  </xsl:for-each>
<xsl:text>
    </xsl:text>

        <xsl:element name="{record/@element}">
       <xsl:for-each select="record/field">
              <xsl:element name="{@element}"><xsl:text>
        </xsl:text>
            <xsl:element name="xsl:value-of">
              <xsl:attribute name="select"><xsl:text>normalize-space($</xsl:text>
                <xsl:value-of select="@element"/>
                <xsl:text>)</xsl:text>                
              </xsl:attribute>
          </xsl:element>  <xsl:text>
      </xsl:text>
          </xsl:element>

    </xsl:for-each>
</xsl:element><xsl:text>
  </xsl:text>
</xsl:element><xsl:text>
</xsl:text>
 
  </xsl:element>
</xsl:element> <!-- template match -->
</xsl:element> <!-- gallery -->
  </xsl:template> 


<xsl:template match="summary/field"><xsl:text>
</xsl:text>
      <xsl:element name="xsl:element">
        <xsl:attribute name="name">
          <xsl:value-of select="@element"/>
        </xsl:attribute><xsl:text>
</xsl:text>
        <xsl:element name="xsl:value-of">
          <xsl:attribute name="select">
            <xsl:value-of select="@xpath"/>
          </xsl:attribute><xsl:text>
</xsl:text>
        </xsl:element><xsl:text>
</xsl:text>
      </xsl:element><xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>

output: gallery.xml (this file is the product of gallery_xhtml.xml and gallery.xsl)
<?xml version="1.0"?>
<gallery>
  <title>Journey to Windsor</title>
  <photo>
    <title>Windsor Castle</title>
    <date>July 2003</date>
    <image>dscn0824.jpg</image>
    <description>
      A bright, red mailbox inside the castle. It seems oddly familiar in an historic setting.
    </description>
  </photo>
</gallery>
« Newer Snippets
Older Snippets »
Showing 1-10 of 21 total  RSS