Permalink
Browse files

fixes #775.

libxml will throw an error if we tried to replace a text node
in a document fragment since it tries to find an element node
or a document node in the parents of the node being replaced.
To make this possible we add an element node and replace that
node instead.
  • Loading branch information...
1 parent d41d950 commit 2d5dccaefbae60cdff95a8efa496d9b648007c1f @jvshahid jvshahid committed Oct 21, 2012
Showing with 21 additions and 9 deletions.
  1. +14 −9 lib/nokogiri/xml/node.rb
  2. +7 −0 test/xml/test_document_fragment.rb
View
@@ -376,17 +376,22 @@ def children= node_or_tags
#
# Also see related method +swap+.
def replace node_or_tags
+ # We cannot replace a text node directly, otherwise libxml will return
+ # an internal error at parser.c:13031, I don't know exactly why
+ # libxml is trying to find a parent node that is an element or document
+ # so I can't tell if this is bug in libxml or not. issue #775.
+ if text?
+ replacee = Nokogiri::XML::Node.new 'dummy', document
+ add_previous_sibling_node replacee
+ unlink
+ return replacee.replace node_or_tags
+ end
+
node_or_tags = coerce(node_or_tags)
+
if node_or_tags.is_a?(XML::NodeSet)
- if text?
- replacee = Nokogiri::XML::Node.new 'dummy', document
- add_previous_sibling_node replacee
- unlink
- else
- replacee = self
- end
- node_or_tags.each { |n| replacee.add_previous_sibling n }
- replacee.unlink
+ node_or_tags.each { |n| add_previous_sibling n }
+ unlink
else
replace_node node_or_tags
end
@@ -8,6 +8,13 @@ def setup
@xml = Nokogiri::XML.parse(File.read(XML_FILE), XML_FILE)
end
+ def test_replace_text_node
+ html = "foo"
+ doc = Nokogiri::XML::DocumentFragment.parse(html)
+ doc.children[0].replace "bar"
+ assert_equal 'bar', doc.children[0].content
+ end
+
def test_fragment_is_relative
doc = Nokogiri::XML('<root><a xmlns="blah" /></root>')
ctx = doc.root.child

0 comments on commit 2d5dcca

Please sign in to comment.