Method: Nokogiri::XML::Node#replace

Defined in:
lib/nokogiri/xml/node.rb

#replace(node_or_tags) ⇒ Object

Replace this Node with node_or_tags.

node_or_tags can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String containing markup.

Returns the reparented node (if node_or_tags is a Node), or NodeSet (if node_or_tags is a DocumentFragment, NodeSet, or String).

Also see related method swap.



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'lib/nokogiri/xml/node.rb', line 405

def replace(node_or_tags)
  raise("Cannot replace a node with no parent") unless parent

  # 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 = parent.coerce(node_or_tags)

  if node_or_tags.is_a?(XML::NodeSet)
    node_or_tags.each { |n| add_previous_sibling(n) }
    unlink
  else
    replace_node(node_or_tags)
  end
  node_or_tags
end