1

Save a Ruby source text file to XML.

http://feeds.dzone.com

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:

#!/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
]]>

Read »
Created by Aaron Created 38 weeks 3 days ago
Category: Programming   Tags: