Select nested xml element where nested tag is the same name using clojure.data.zip

210 Views Asked by At

I have a bit of XML that I'm wrangling using clojure.data.zip.xml. That XML has elements with the same name as nested elements:

<things>
  <thing>
    <thing>Want this</thing>
    <thingattr>...but not this</thingattr>
  </thing>
  <thing>
    <thing>Select this</thing>
    <thingattr>...again, not this</thingattr>
  </thing>
</things>

However, accessing the inner element seems to be beyond my reach with the xml-> function in clojure.data.zip.xml. If, however, the nested element does not share the same name as the parent, all works as expected:

(ns xmlzip.core
  (:require [clojure.xml :as xml]
            [clojure.zip]
            [clojure.data.zip.xml :as z])
  (:gen-class))

(defn parse [s]
  (clojure.xml/parse
   (java.io.ByteArrayInputStream. (.getBytes s))))

(def example1 (clojure.zip/xml-zip (parse "
<things>
  <thing>
    <thing>Want this</thing>
    <thingattr>...but not this</thingattr>
  </thing>
  <thing>
    <thing>Select this</thing>
    <thingattr>...again, not this</thingattr>
  </thing>
</things>
")))

(def example2 (clojure.zip/xml-zip (parse "
<things>
  <thing>
    <subthing>Want this</subthing>
    <thingattr>...but not this</thingattr>
  </thing>
  <thing>
    <subthing>Select this</subthing>
    <thingattr>...again, not this</thingattr>
  </thing>
</things>
")))


(z/xml-> example2 :thing :subthing z/text)
;; ("Want this" "Select this") ;hooray!

(z/xml-> example1 :thing :thing z/text)
;; ("Want this...but not this" "Select this...again, not this") ;boo, hiss.

I suspect that this may be an unaddressed case in clojure.data.zip.xml, but I am hoping that someone can show me the proper usage if I am simply misunderstanding how to use the library.

0

There are 0 best solutions below