Skip to content

Instantly share code, notes, and snippets.

@akostadinov
Forked from gioele/add_child_ns.rb
Last active June 9, 2016 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akostadinov/367ce3855289cdb9bd3d83896f843b0f to your computer and use it in GitHub Desktop.
Save akostadinov/367ce3855289cdb9bd3d83896f843b0f to your computer and use it in GitHub Desktop.
Nokogiri `add_child` does not copy namespaces
#!/usr/bin/env ruby
# see https://github.com/sparklemotion/nokogiri/issues/1200
require 'nokogiri'
src =<<EOD
<wrapper xmlns="ns">
<record xml:id="r1" xmlns:extra="extra">
<field>aaa</field>
<field extra:type="second">bbb</field>
</record>
</wrapper>
EOD
src_doc = Nokogiri::XML(src)
record = src_doc.at('//base:field[. = "bbb"]', {'base' => "ns"})
puts "== Original document"
puts src_doc.to_xml
# if we instead add `record.dup` here, things will work properly
src_doc.root.add_child(record)
puts
puts "== New document"
puts "== There should be a xmlns declaration in the last field element but it is not"
puts src_doc.to_xml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment