Advertisement
Guest User

Untitled

a guest
Sep 9th, 2011
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. ;clojure pretty print functions for lazy-xml -> xml-zip zippers.
  2. ;author: Keith Wyss
  3.  
  4. (let [tabs (cycle '(" "))]
  5. (defn attrstr [attr]
  6. "generates a string to insert into xml for :attr keywork in zipper"
  7. (let [ks (keys attr)
  8. ans (apply str
  9. (for [x ks]
  10. (str (name x) "=" (x attr))
  11. )
  12. )]
  13. (if (= ans "")
  14. ans
  15. (str " " ans)
  16. )
  17. )
  18. )
  19. (defn prxmlzip [node stck strvec depth down?]
  20. "Returns a str-seq that apply-str will turn into an xml-rep of an xml zipper"
  21. (if down?
  22. ;case for going deeper in xml tree
  23. (let [elem (first node)]
  24. (if (nil? (clojure.zip/down node)) ;case element is a leaf node
  25. (let [new-strvec (conj strvec (str " " elem))
  26. ;adds the entry with tabbing
  27. new-strvecifup (conj new-strvec (str " "
  28. "</" (peek stck) ">")) ;add closing tag if popping
  29. rght (clojure.zip/right node)
  30. up (clojure.zip/up node)]
  31. (if rght
  32. (recur rght (pop stck) new-strvec depth true)
  33. (recur up (pop stck) new-strvecifup (dec depth) false)
  34. ; this recur is a pop in the zipper
  35. )
  36. )
  37. ;element is not a leaf node
  38. (let [new-stck (conj stck (name (:tag elem))) ;add the tag to the stack so that it closes correctly
  39. tag (name (:tag elem))
  40. new-strvec (conj strvec "\n" (apply str (take depth tabs))
  41. "<" tag (attrstr (:attr elem)) ">") ;add tag and attr with tabs
  42. down (clojure.zip/down node)
  43. ]
  44. (recur down new-stck new-strvec (inc depth) true)
  45. )
  46. )
  47. )
  48. ;case if popping up xml tree
  49. (let [up (clojure.zip/up node)
  50. rght (clojure.zip/right node)
  51. newstrvecifup (conj strvec "\n" (str (apply str (take (dec depth) tabs))
  52. "</" (peek stck) ">"))]
  53. ;we will look for a tree to traverse downward or travel up towards the root and quit
  54. (cond rght
  55. (recur rght stck strvec depth true)
  56. (and (> depth 0) up) (recur up (pop stck) newstrvecifup (dec depth) false)
  57. :else strvec
  58. )
  59. )
  60. );end if down
  61. )
  62.  
  63. (defn ppxml [node]
  64. "Takes a node and returns a string of it's xml subtree"
  65. (apply str (next (prxmlzip node '() [] 0 true))) ;next effectively chomps leading \n
  66. )
  67. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement