Skip to content

Instantly share code, notes, and snippets.

@jasonjckn
Created June 4, 2011 19:45
Show Gist options
  • Save jasonjckn/1008265 to your computer and use it in GitHub Desktop.
Save jasonjckn/1008265 to your computer and use it in GitHub Desktop.
(ns xml
(:use
[eu.dnetlib.clojure.clarsec]
[eu.dnetlib.clojure.monad]))
;; Parsing simplified XML:
;;
;; Sample Input:
(def input
" <library>
<book>
<title>Joy of Clojure</title>
<author>Fogus</author>
</book>
<book>
<title>Structured and Interpretation of Computer Programs</title>
<author>MIT</author>
</book>
</library>")
(defn arrows [p] (between (symb "<") (symb ">") p))
(def open-tag (arrows identifier))
(defn close-tag [expect-name] (arrows (symb (str "/" expect-name))))
(defn element [p]
(let-bind [tag-name open-tag
contents p
_ (close-tag tag-name)]
(result {(keyword tag-name) contents})))
(def xml
(let [list$ #(flatten (apply list %&))]
(element
(<|> (<$> #(apply merge-with list$ %) (many1 (lazy xml)))
(stringify (many (<|> letter space)))))))
(defn -main []
(println (:value (parse xml input))))
;; (-main)
;; Output:
;; {:library
;; {:book ({:author Fogus,
;; :title Joy of Clojure}
;; {:author MIT,
;; :title Structured and Interpretation of Computer Programs})}}
@jasonjckn
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment