Node.dup with attributes?

188 views
Skip to first unread message

rpark

unread,
Feb 7, 2010, 9:46:25 PM2/7/10
to nokogiri-talk
Hi, just wondering if there is an easier way to duplicate/clone a
node, preserving all of the source node's attributes? Currently I'm
doing this (from within an instance of Node):

node = self.dup(0)
attr = self.attributes
attr.each { |k, v| node[k] = v } unless attr.empty?
node

Aaron Patterson

unread,
Feb 7, 2010, 10:22:30 PM2/7/10
to nokogi...@googlegroups.com
On Sun, Feb 7, 2010 at 6:46 PM, rpark <nonf...@gmail.com> wrote:
> Hi, just wondering if there is an easier way to duplicate/clone a
> node, preserving all of the source node's attributes? Currently I'm
> doing this (from within an instance of Node):

If you're doing a shallow copy, then no. The shallow copy only copies
the immediate node, so when it says shallow, it *means* shallow. heh.

A deep copy would do the trick, but you'd have to unlink the child
nodes. For example:

node = other_node.dup
node.children.each { |x| x.unlink }

--
Aaron Patterson
http://tenderlovemaking.com/

Reply all
Reply to author
Forward
0 new messages