From: Bob Hutchison Date: 2005-10-11T23:49:34+09:00 Subject: Re: help with htree Hi, Thanks for the pointer to HTree. On Oct 10, 2005, at 5:31 PM, Ara.T.Howard wrote: > On Tue, 11 Oct 2005, Ara.T.Howard wrote: > > >> >> i'm trying use the htree library for a relatively simple task in >> the hope that >> it's parser will outlive one i roll on my own - it certainly seems >> robust as >> it is... in any case i'm trying to do the following >> >> - scan a doc for any elements that have a certain attribute >> - iff the element with that attribute is of a certain class (b, >> i, pre, etc) >> then i'll want to replace the text of that element in-place >> - finally, a new doc will be produced >> >> any hints appreciated. i've got a hand parsed version running now >> - but >> really would like to use htree. >> > > on a related note, does this seem right to people: > > irb(main):019:0> HTree("
").display_html '' > => "" > HTML doesn't have an element
it has
, like the old

tag. Though most browsers support it, though some will require


(note the space). So, technically I suppose HTree is correct. > notice it ate the closing slash. i know that's bad form, but i > wonder if this > is intended or not... > Give this code a shot, I think this is what you want assuming I read you correctly. Had to dump yaml a few times to figure out what was going on :-) Cheers, Bob require 'htree' def handle_element(elem) new_element_name = elem.element_name().to_s new_attributes = Hash.new().merge(elem.attributes) elem.attributes.each{ | name, value | if "replace" == name.to_s then new_element_name = value.to_s new_attributes.delete(name) break end } if (elem.kind_of?(HTree::Text)) new_elem = elem.to_s elsif (elem.kind_of?(HTree::Elem)) children = [] elem.children.each(){ | child | if (child.kind_of?(HTree::Text)) then children << child.to_s elsif (child.kind_of?(HTree::Elem)) children << handle_element(child) end } new_elem = HTree::Elem.new(new_element_name, new_attributes, children) end return new_elem end def handle_root(root) children = [] root.children.each(){ | elem | children << handle_element(elem) if (elem.kind_of?(HTree::Elem)) } HTree::Doc.new(children) end html = %Q{

hello there, how are you?

} tree = HTree(html) new_tree = handle_root(tree) puts tree.display_html("") puts new_tree.display_html("") __EOF__ ---- Bob Hutchison -- blogs at Recursive Design Inc. -- Raconteur --