Merging 2 or more XML documents

require 'line-tree'

# If I have an XML structure as follows:
s =<<EOF
a
  b
    c2
  b
EOF

# ... and I want to merge it with this XML structure:
s2 =<<EOF
a
  b
    c3
  b
    eee
EOF

# then it should result in the XML structure below:
s3 =<<EOF
a
  b
    c2
    c3
  b
    eee
EOF


mdoc = Rexle.new LineTree.new(s).to_xml
doc = Rexle.new LineTree.new(s2).to_xml

def scan(mdoc, e, axpath=[], tally=[])

  axpath << e.name
  tally << e.name

  # does the xpath match with the master doc?
  node = mdoc.element axpath.join('/')

  unless node then
    index = "[%s]" % (tally.grep(e.parent.name).length)
    xpath = axpath[0..-2].join('/') + index
    mdoc.element(xpath).add e
  end
  
  e.elements.each {|x| scan mdoc, x, axpath.clone, tally }

end

scan mdoc, doc.root
puts mdoc.xml pretty: true

<?xml version='1.0' encoding='UTF-8'?>
<a>
  <b>
    <c2></c2>
    <c3></c3>
  </b>
  <b>
    <eee></eee>
  </b>
</a>
Tags:
Source:
1420hrs.txt
Published:
09-10-2013 14:20