Search code examples
xmlclojure

Searching xml in Clojure


I have the following sample xml:

<data>
  <products>
    <product>
      <section>Red Section</section>
      <images>
        <image>img.jpg</image>
        <image>img2.jpg</image>
      </images>
    </product>
    <product>
      <section>Blue Section</section>
      <images>
        <image>img.jpg</image>
        <image>img3.jpg</image>
      </images>
    </product>
    <product>
      <section>Green Section</section>
      <images>
        <image>img.jpg</image>
        <image>img2.jpg</image>
      </images>
    </product>
  </products>
</data>

I know how to parse it in Clojure

(require '[clojure.xml :as xml])
(def x (xml/parse 'location/of/that/xml'))

This returns a nested map describing the xml

{:tag :data,
 :attrs nil,
 :content [
     {:tag :products,
      :attrs nil,
      :content [
          {:tag :product,
           :attrs nil,
           :content [] ..

This structure can of course be traversed with standard Clojure functions, but it may turn out to be really verbose, especially if compared to, for instance, querying it with XPath. Is there any helper to traverse and search such structure? How can I, for example

  • get a list of all <product>
  • get only the product whose <images> tag contains an <image> with text "img2.jpg"
  • get the product whose section is "Red Section"

Thanks


Solution

  • You can use a library like clj-xpath