Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
XML parsing and clojure.zip
;;; XML parsing and clojure.zip
;;; There's got to be a cleaner way to do this.
;;; I have code like this:
(defn jdks-loc [xml-zipper]
(zip/down
(first
(filter #(let [n (zip/node %)]
(and (map? n) (= :jdks (:tag n))))
(iterate zip/right (zip/down xml-zipper))))))
(defn jdk-details [jdk-loc]
(reduce (fn [m elt]
(if (#{:name :home} (:tag elt))
(assoc m (:tag elt) (apply str (:content elt)))
m))
{}
(zip/children jdk-loc)))
(defn jdks [loc]
(map jdk-details (take-while identity (iterate zip/right loc))))
(defn do-it []
(jdks (jdks-loc (zip/xml-zip (ci-config-xml)))))
;;; To get a result like this:
user=> (do-it)
({:home "/usr/java/jdk1.6.0_20", :name "Sun JDK 1.6.0_20"}
{:home "/var/lib/hudson/tools/Sun_JDK_1.5.0_22", :name "Sun JDK 1.5.0_22"}
{:home "/usr/java/ibm-java2-x86_64-50", :name "IBM Java SDK 5.0-12.3"}
{:home "/usr/java/java-1.6.0-openjdk-1.6.0.0.x86_64", :name "OpenJDK 1.6.0.0-1.16.b17.el5"}
{:home "/usr/java/jrockit-jdk1.5.0_28-R28.1.3-4.0.1", :name "JRockit JDK 1.5.0_28-R28.1.3-4.0.1"}
{:home "/usr/java/jrockit-jdk1.6.0_24-R28.1.3-4.0.1", :name "JRockit JDK 1.6.0_24-R28.1.3-4.0.1"})
;;; From XML like this:
;; <?xml version='1.0' encoding='UTF-8'?>
;; <hudson>
;; <version>1.386</version>
;; <!-- ... bunch more tags ... -->
;; <jdks>
;; <jdk>
;; <name>Sun JDK 1.6.0_20</name>
;; <home>/usr/java/jdk1.6.0_20</home>
;; <properties/>
;; </jdk>
;; <jdk>
;; <name>Sun JDK 1.5.0_22</name>
;; <home>/var/lib/hudson/tools/Sun_JDK_1.5.0_22</home>
;; <properties/>
;; </jdk>
;; <jdk>
;; <name>IBM Java SDK 5.0-12.3</name>
;; <home>/usr/java/ibm-java2-x86_64-50</home>
;; <properties/>
;; </jdk>
;; <jdk>
;; <name>OpenJDK 1.6.0.0-1.16.b17.el5</name>
;; <home>/usr/java/java-1.6.0-openjdk-1.6.0.0.x86_64</home>
;; <properties/>
;; </jdk>
;; <jdk>
;; <name>JRockit JDK 1.5.0_28-R28.1.3-4.0.1</name>
;; <home>/usr/java/jrockit-jdk1.5.0_28-R28.1.3-4.0.1</home>
;; <properties/>
;; </jdk>
;; <jdk>
;; <name>JRockit JDK 1.6.0_24-R28.1.3-4.0.1</name>
;; <home>/usr/java/jrockit-jdk1.6.0_24-R28.1.3-4.0.1</home>
;; <properties/>
;; </jdk>
;; </jdks>
;; <!-- ... bunch more tags ... -->
;; </hudson>
@stuartsierra

This comment has been minimized.

Copy link
Owner Author

@stuartsierra stuartsierra commented Sep 2, 2011

;;; Chouser answers: use data.zip!

(ns clojure.build.ci.generator
  (:use [clojure.java.io :only (file)])
  (:require [clojure.xml :as xml]
            [clojure.zip :as zip]
            [clojure.data.zip.xml :as dzx]))

;;; ... code omitted ...

(defn jdks [xml-zipper]
  (map (fn [loc]
         {:name (dzx/xml1-> loc :name dzx/text)
          :home (dzx/xml1-> loc :home dzx/text)})
       (dzx/xml-> xml-zipper :jdks :jdk)))

(defn doit []
  (jdks (zip/xml-zip (ci-config-xml))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.