hickory
hickory copied to clipboard
Deleting elements with selectors?
Would be nice to be able to modify trees with selectors. Something like
(hs/remove selector-fn hickory-tree)
This is more general than #28.
Hickory lets you make any modification you want to the tree using Clojure's Zipper interface, just use select-locs or select-next-loc instead of select, and you'll be returned a Clojure zipper that you can do modifications on.
and you'll be returned a Clojure zipper that you can do modifications on.
Thanks. I will try it out and will post an example here for the reference.
I finally got down to figuring this out:
(defn hickory-remove [selector-fn hickory-tree]
(loop [zip (hickory.zip/hickory-zip hickory-tree)
next (hs/select-next-loc selector-fn zip)]
(if next
(let [new-zip (zip/remove next)]
(recur new-zip (hs/select-next-loc selector-fn new-zip)))
(zip/root zip))))
Usage:
(hickory-remove (hs/node-type :comment) tt)
I think it's a useful utility, but feel free to close if you think it's not worth including into the package.
An actual example in the docs (such as this one, or even simpler) of combining selectors and zippers to modify some HTML would be helpful!
here an even more generic function:
(defn hickory-update [selector-fn hickory-tree zip-fn]
(loop [zip (hickory.zip/hickory-zip hickory-tree)
next (hickory.select/select-next-loc selector-fn zip)]
(if next
(let [new-zip (zip-fn next)]
(recur new-zip (hickory.select/select-next-loc selector-fn new-zip)))
(zip/root zip))))
; example: replace h3 by h2 tag
(defn replace-h3-h2 [t]
(hickory-update
(hickory.select/tag :h3)
t
#(zip/edit
%
(fn [n]
(assoc n :tag :h2)))))