Advertisement
cd62131

parse csv to xml

Dec 4th, 2017
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.86 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. require 'rexml/document'
  3.  
  4. source = 'root,ELEM,a,name,a1,ATTR,b,bbb1,ATTR,b,bbb2,ELEM,a2'
  5. elems = source.split /,/
  6. doc = REXML::Document.new "<#{elems.shift}/>"
  7. elems.slice_before {|e| e == 'ELEM' }.each do |e|
  8.   e.shift # delete 'ELEM'
  9.   a = REXML::Element.new e.shift
  10.   e.slice_before {|ee| ee == 'ATTR' }.each do |ee|
  11.     if ee.first != 'ATTR'
  12.       ee.each_slice(2) do |eee|
  13.         if eee.size == 1
  14.           a.text, = eee
  15.         else
  16.           a.add_attribute *eee
  17.         end
  18.       end
  19.     else
  20.       ee.shift # delete 'ATTR'
  21.       b = REXML::Element.new ee.shift
  22.       ee.each_slice(2) do |eee|
  23.         if eee.size == 1
  24.           b.text, = eee
  25.         else
  26.           b.add_attribute *eee
  27.         end
  28.       end
  29.       a.elements << b
  30.     end
  31.   end
  32.   doc.root << a
  33. end
  34. open('hoge.xml', 'w') {|f| doc.write f, 2; f.puts }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement