Index: ext/xml/ruby_xml_node.c =================================================================== --- ext/xml/ruby_xml_node.c (revision 220) +++ ext/xml/ruby_xml_node.c (working copy) @@ -327,7 +327,7 @@ chld = cnode->node; - if ( chld->parent != NULL || chld->doc != NULL ) { + if ( chld->parent != NULL || chld->doc != NULL || chld->type == XML_TEXT_NODE ) { chld=xmlCopyNode(chld,1); copied=1; if ( do_raise == 1 ) @@ -342,7 +342,9 @@ } // wish I could return a new wrapped chld, but ruby only returns the rhs - return ruby_xml_node2_wrap(cXMLNode,chld); + // chld is freed if xmlAddChild() successed and chld->type == XML_TEXT_NODE, + // so we need another copy of cnode->node. + return ruby_xml_node2_wrap(cXMLNode,cnode->node); } /* Index: ext/xml/libxml.rb =================================================================== --- ext/xml/libxml.rb (revision 220) +++ ext/xml/libxml.rb (working copy) @@ -72,6 +72,10 @@ def <=>(other) to_s <=> other.to_s end + + def clone + copy(false) + end end class XML::Attr Index: tests/tc_xml_node_copy.rb =================================================================== --- tests/tc_xml_node_copy.rb (revision 0) +++ tests/tc_xml_node_copy.rb (revision 0) @@ -0,0 +1,40 @@ +require "libxml_test" +require "xml/libxml" +require 'test/unit' + +# see mailing list archive +# [libxml-devel] Segmentation fault when add the cloned/copied node +# 2007/11/27 20:51 +class TC_XML_Node_Copy < Test::Unit::TestCase + def setup + str = <<-STR + +
foo
+
bar
+ + STR + + doc = XML::Parser.string(str).parse + + xpath = "//div" + @div1 = doc.find(xpath).to_a[0] + @div2 = doc.find(xpath).to_a[1] + end + + def test_libxml_node_copy_not_segv + @div2.each do |child| + c = child.copy(false) + @div1.child_add(c) + end + assert @div1.to_s =~ /foo/ + end + + def test_libxml_node_clone_not_segv + @div2.each do |child| + c = child.clone + @div1.child_add(c) + end + assert @div1.to_s =~ /foo/ + end + +end # TC_XML_Node_Copy