Save a Ruby source text file to XML.
#!/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>