Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Nokogiri copy node between documents and DOMException WRONG_DOCUMENT_ERR
require 'nokogiri'
# The following illustrates unexpected behavior of the Nokogiri::XML::Document.add_child method.
# When called from a new document, the behavior is different depending on if the argument
# is a newly created node or duplicate node.
# String of XML for Nokogiri to parse.
dummy_xml = '<?xml version="1.0" encoding="UTF-8"?>
<root>
<Dummy>Text1</Dummy>
<Dummy>Text2</Dummy>
<Dummy>Text3</Dummy>
</root>'
# Existing document from which to copy a node.
x_doc = Nokogiri::XML::Document.parse( dummy_xml )
# New document into which the copied node will go.
n_doc = Nokogiri::XML::Document.new
# Duplicate the node to copy to new document.
duplicate = x_doc.xpath("/root/Dummy[2]").first.dup
# Fresh node created for new document.
fresh = Nokogiri::XML::Node.new( "freshNode", n_doc )
# Using add_child method of new document with duplicate will fail.
begin
n_doc.add_child( duplicate )
rescue RuntimeError => run_err
puts run_err.to_s
end
# Using add_child of new document with freshly created node will work.
# Using add_child of freshly created node with duplicate node will work.
begin
n_doc.add_child( fresh )
n_doc.root.add_child( duplicate )
rescue RuntimeError => run_err
puts run_err.to_s
end
# Print document.
puts "Document with fresh node:"
puts n_doc
# For contrast, using root= of newly created document with duplicate node will work.
# New document into which the copied node will go.
n_doc = Nokogiri::XML::Document.new
# Setting the duplicate node as root will work.
begin
n_doc.root=duplicate
rescue RuntimeError => run_err
puts run_err.to_s
end
puts "Document with duplicate node:"
# Print document
puts n_doc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.