Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Use a <a href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/for">for comprehension</a>, these yield lazy sequences.</p> <p>Here's the code for you. I've taken the time to make it runnable on the command line; you only need to replace the name of the parsed XML file.</p> <p><strong>Caveat 1:</strong> avoid def-ing your variables. Use local variables instead.</p> <p><strong>Caveat 2:</strong> this is the Java API for XML, so there objects are mutable; since you have a lazy sequence, if any changes happen to the mutable DOM tree while you're iterating, you might have unpleasant race changes.</p> <p><strong>Caveat 3:</strong> even though this is a lazy structure, the whole DOM tree is already in memory anyway <em>(I'm not really sure about this last comment, though. I think the API tries to defer reading the tree in memory until needed, but, no guarantees)</em>. So if you run into trouble with big XML documents, try to avoid the DOM approach.</p> <pre><code>(require ['clojure.java.io :as 'io]) (import [javax.xml.parsers DocumentBuilderFactory]) (import [org.xml.sax InputSource]) (def dbf (DocumentBuilderFactory/newInstance)) (doto dbf (.setValidating false) (.setNamespaceAware true) (.setIgnoringElementContentWhitespace true)) (def builder (.newDocumentBuilder dbf)) (def doc (.parse builder (InputSource. (io/reader "C:/workspace/myproject/pom.xml")))) (defn lazy-child-list [element] (let [nodelist (.getChildNodes element) len (.getLength nodelist)] (for [i (range len)] (.item nodelist i)))) ;; To print the children of an element (-&gt; doc (.getDocumentElement) (lazy-child-list) (println)) ;; Prints clojure.lang.LazySeq (-&gt; doc (.getDocumentElement) (lazy-child-list) (class) (println)) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload