annotate src/clojure/contrib/lazy_xml/with_pull.clj @ 10:ef7dbbd6452c

added clojure source goodness
author Robert McIntyre <rlm@mit.edu>
date Sat, 21 Aug 2010 06:25:44 -0400
parents
children
rev   line source
rlm@10 1 ; Copyright (c) Chris Houser, Dec 2008. All rights reserved.
rlm@10 2 ; The use and distribution terms for this software are covered by the
rlm@10 3 ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
rlm@10 4 ; which can be found in the file epl-v10.html at the root of this distribution.
rlm@10 5 ; By using this software in any fashion, you are agreeing to be bound by
rlm@10 6 ; the terms of this license.
rlm@10 7 ; You must not remove this notice, or any other, from this software.
rlm@10 8
rlm@10 9 ; optional module to allow lazy-xml to use pull parser instead of sax
rlm@10 10
rlm@10 11 (in-ns 'clojure.contrib.lazy-xml)
rlm@10 12 (import '(org.xmlpull.v1 XmlPullParser XmlPullParserFactory))
rlm@10 13
rlm@10 14 (defn- attrs [xpp]
rlm@10 15 (for [i (range (.getAttributeCount xpp))]
rlm@10 16 [(keyword (.getAttributeName xpp i))
rlm@10 17 (.getAttributeValue xpp i)]))
rlm@10 18
rlm@10 19 (defn- ns-decs [xpp]
rlm@10 20 (let [d (.getDepth xpp)]
rlm@10 21 (for [i (range (.getNamespaceCount xpp (dec d)) (.getNamespaceCount xpp d))]
rlm@10 22 (let [prefix (.getNamespacePrefix xpp i)]
rlm@10 23 [(keyword (str "xmlns" (when prefix (str ":" prefix))))
rlm@10 24 (.getNamespaceUri xpp i)]))))
rlm@10 25
rlm@10 26 (defn- attr-hash [xpp]
rlm@10 27 (into {} (concat (ns-decs xpp) (attrs xpp))))
rlm@10 28
rlm@10 29 (defn- pull-step [xpp]
rlm@10 30 (let [step (fn [xpp]
rlm@10 31 (condp = (.next xpp)
rlm@10 32 XmlPullParser/START_TAG
rlm@10 33 (cons (struct node :start-element
rlm@10 34 (keyword (.getName xpp))
rlm@10 35 (attr-hash xpp))
rlm@10 36 (pull-step xpp))
rlm@10 37 XmlPullParser/END_TAG
rlm@10 38 (cons (struct node :end-element
rlm@10 39 (keyword (.getName xpp)))
rlm@10 40 (pull-step xpp))
rlm@10 41 XmlPullParser/TEXT
rlm@10 42 (let [text (.trim (.getText xpp))]
rlm@10 43 (if (empty? text)
rlm@10 44 (recur xpp)
rlm@10 45 (cons (struct node :characters nil nil text)
rlm@10 46 (pull-step xpp))))))]
rlm@10 47 (lazy-seq (step xpp))))
rlm@10 48
rlm@10 49 (def ^{:private true} factory
rlm@10 50 (doto (XmlPullParserFactory/newInstance)
rlm@10 51 (.setNamespaceAware true)))
rlm@10 52
rlm@10 53 (defn- parse-seq-pull [s]
rlm@10 54 (let [xpp (.newPullParser factory)]
rlm@10 55 (.setInput xpp s)
rlm@10 56 (pull-step xpp)))
rlm@10 57
rlm@10 58 (def has-pull true)