Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- require 'rexml/document'
- source = 'root,ELEM,a,name,a1,ATTR,b,bbb1,ATTR,b,bbb2,ELEM,a2'
- elems = source.split /,/
- doc = REXML::Document.new "<#{elems.shift}/>"
- elems.slice_before {|e| e == 'ELEM' }.each do |e|
- e.shift # delete 'ELEM'
- a = REXML::Element.new e.shift
- e.slice_before {|ee| ee == 'ATTR' }.each do |ee|
- if ee.first != 'ATTR'
- ee.each_slice(2) do |eee|
- if eee.size == 1
- a.text, = eee
- else
- a.add_attribute *eee
- end
- end
- else
- ee.shift # delete 'ATTR'
- b = REXML::Element.new ee.shift
- ee.each_slice(2) do |eee|
- if eee.size == 1
- b.text, = eee
- else
- b.add_attribute *eee
- end
- end
- a.elements << b
- end
- end
- doc.root << a
- end
- open('hoge.xml', 'w') {|f| doc.write f, 2; f.puts }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement