title: How do I merge two XML files into one using Nokogiri?
body: <p>I have two XML files and want to merge them, but the tags that are already there should not be changed:</p>
  
  <p>XML 1:</p>
  
  <pre><code>&lt;?xml version="1.0"?&gt;
  &lt;formX xmlns="sdu:x"&gt;
    &lt;identify&gt;
      &lt;mat&gt;8&lt;/mat&gt;
    &lt;/identify&gt;
  &lt;/formX&gt;
  </code></pre>
  
  <p>XML 2:</p>
  
  <pre><code>&lt;?xml version="1.0"?&gt;
  &lt;formX xmlns="sdu:x"&gt;
    &lt;identify&gt;
      &lt;mat&gt;9999&lt;/mat&gt;
      &lt;name&gt;John Smith&lt;/name&gt;
    &lt;/identify&gt;
  &lt;/formX&gt;
  </code></pre>
  
  <p>I want the result to be like this:</p>
  
  <pre><code>&lt;?xml version="1.0"?&gt;
  &lt;formX xmlns="sdu:x"&gt;
    &lt;identify&gt;
      &lt;mat&gt;8&lt;/mat&gt;
      &lt;name&gt;John Smith&lt;/name&gt;
    &lt;/identify&gt;
  &lt;/formX&gt;
  </code></pre>
  
  <p>The previous tags should have the same values but with the addition of the new ones.
  Is that possible using Nokogiri? How?</p>
  
  <p>At first I tried without Nokogiri using:</p>
  
  <pre><code>xml1 = Hash.from_xml('&lt;?xml version="1.0"?&gt;
  &lt;formX xmlns="sdu:x"&gt;
    &lt;identify&gt;
      &lt;mat&gt;8&lt;/mat&gt;
    &lt;/identify&gt;
  &lt;/formX&gt;')
  </code></pre>
  
  <p>But when I convert back to xml (xml1.to_xml) I get in wrong format:</p>
  
  <pre><code>"&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;hash&gt;\n  &lt;formX&gt;\n    &lt;xmlns&gt;sdu:x&lt;/xmlns&gt;\n    &lt;identify&gt;\n      &lt;mat&gt;8&lt;/mat&gt;\n    &lt;/identify&gt;\n  &lt;/formX&gt;\n&lt;/hash&gt;\n"
  </code></pre>
  
  <p>Using Nokogiri, I came up with this solution, but really, it is so ugly and have a bug. If the xml2 doesnt have a element it will crash:</p>
  
  <pre><code>require 'nokogiri'
  
  s = "&lt;formAposentadoria xmlns=\"spu:aposentadoria\"&gt;&lt;identificacao&gt;&lt;matricula&gt;8&lt;/matricula&gt;&lt;/identificacao&gt;&lt;/formAposentadoria&gt;"
  xml1 = Nokogiri::XML.parse s
  
  s2 = "&lt;formAposentadoria xmlns=\"spu:aposentadoria\"&gt;&lt;identificacao&gt;&lt;matricula&gt;9&lt;/matricula&gt;&lt;nome&gt;John&lt;/nome&gt;&lt;/identificacao&gt;&lt;/formAposentadoria&gt;"
  xml2 = Nokogiri::XML.parse s2
  
  def node_list elem, &amp;proc
    return [] unless elem.class == Nokogiri::XML::Element
    str = proc.call(elem)
    [str] + elem.children.inject([]){|a,c| a+node_list(c,&amp;proc)}.map{|e| "#{str}/#{e}"}
  end
  
  node_list(xml1.root){|e| e.name}.each do |x|
    caminho = '//xmlns:' + x.gsub('/', '/xmlns:')
    puts caminho
    if xml2.at_xpath( caminho ).children.children.count == 0
      xml2.at_xpath( caminho ).content = xml1.at_xpath( caminho ).content
    end
  end
  
  puts xml2.to_xml
  </code></pre>