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

Save a Ruby source text file to XML. (See related posts)

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>

You need to create an account or log in to post comments to this site.


Click here to browse all 4881 code snippets

Related Posts