diff --git a/ext/java/nokogiri/XmlNode.java b/ext/java/nokogiri/XmlNode.java
index 5e126817fca..e7b21c939ff 100644
--- a/ext/java/nokogiri/XmlNode.java
+++ b/ext/java/nokogiri/XmlNode.java
@@ -1542,6 +1542,10 @@ protected IRubyObject adoptAs(ThreadContext context, AdoptScheme scheme,
try {
Document prev = otherNode.getOwnerDocument();
Document doc = thisNode.getOwnerDocument();
+ if (doc == null & thisNode instanceof Document) {
+ // we are adding the new node to a new empty document
+ doc = (Document) thisNode;
+ }
clearXpathContext(prev);
clearXpathContext(doc);
if (doc != null && doc != otherNode.getOwnerDocument()) {
diff --git a/test/xml/test_node_reparenting.rb b/test/xml/test_node_reparenting.rb
index 02fbe56cc52..2375035c20e 100644
--- a/test/xml/test_node_reparenting.rb
+++ b/test/xml/test_node_reparenting.rb
@@ -197,6 +197,17 @@ class TestNodeReparenting < Nokogiri::TestCase
end
end
+ describe "given the new document is empty" do
+ it "adds the node to the new document" do
+ doc1 = Nokogiri::XML.parse("3")
+ doc2 = Nokogiri::XML::Document.new
+ node = doc1.at_xpath("//value")
+ node.remove
+ doc2.add_child(node)
+ assert_match /3<\/value>/, doc2.to_xml
+ end
+ end
+
describe "given a parent node with a default namespace" do
before do
@doc = Nokogiri::XML(<<-eoxml)