ruby - Nokogiri: copy node and add new parent to copy? -
any idea how copy node , give new parent, goal of writing copy new file?
i've noticed when reassign 1 node another's parent, nothing happens. example,
doc.xpath("/child").each do|child| # copy node new structure. tried dup() copyofchild = child # create new node become newdoc's parent mom = nokogiri::xml::node.new('mom', copyofchild) copyofchild.parent = mom puts copyofchild # lists <child>...</child>, not <mom><child>...</child></mom> # write newdoc file... end the 1 example on docs page shows analogous working, although they're reassigning 1 item in structure parent of item in same structure.
thanks!
starting this:
require 'nokogiri' xml = '<xml><bar>text</bar></xml>' doc = nokogiri::xml(xml) bar = doc.at('bar') bar.parent.children = '<foo>' + bar.to_xml + '</foo>' puts doc.to_xml which looks like:
<?xml version="1.0"?> <xml> <foo> <bar>text</bar> </foo> </xml> alternately, can like:
bar = doc.at('bar') bar.replace('<foo>' + bar.to_xml + '</foo>') part of problem in code xpath accessor:
"/child" doesn't think. finds top-level <child> node, not 1 farther in tree. in example xml it'd equivalent <xml> node. perhaps want //child finds <child> nodes throughout document.
personally, prefer css accessors on xpath. both nicely supported nokogiri, , both make things easier other, it's familiar both.
Comments
Post a Comment