Frage

Hier können wir annehmen, einige XML haben etwa so:

<a>
  <b>
    <c>text</c>
    <d>
      <e>text</e>
      <f>
        ... lots of cruft here ..
      </f>
    </d>
  </b>
  <b>
    ...
  </b>
  <!-- more b sub-trees --> 
</a>

Nun, auf der Suche durch die Proben in zip_filter / xml.clj, ich habe herausgefunden, wie man einzelne Werte zu bekommen, dass ich interessiert bin.

Ich frage mich, wie ich so etwas wie eine Liste von Paaren von Textwerten von (c e) tun würde.

EDIT:

Hier finden Sie einige Arbeitscode, aber es ist ziemlich hässlich. Nicht fragen, für trivial Refactoring, aber gibt es eine schönere Art und Weise, dass Reißverschluss uns geben, dies zu tun?

(defn extract-data [xml] 
  (let [items (x/xml-> xml zf/descendants :Item)     ;items not top-level
        getAttributes  #(x/xml1-> % :ItemAttributes) ;items have itemattributes
        getASIN        #(x/xml1-> % :ASIN x/text)    ;items have ASINs
        getTitle       #(x/xml1-> % :Title x/text)   ;itemattributes have Titles
        getAuthor      #(x/xml1-> % :Author x/text)] ;itemattributes have Authors
    (map 
       ;build a function to get everything we need from the items, and apply
      #(let [attributes (getAttributes %)] ;get the attributes, we'll use it twice
         (list 
           (getASIN %) 
           (getTitle attributes) 
           (getAuthor attributes)))
      items)))
War es hilfreich?

Lösung

Je nach Clojure-Version verwenden, können Sie die juxt Funktion nützlich finden. Geposteten Code (nur relevante Teile):

(defn extract-data
  [xml] 
  (let [...]
    (map (juxt getASIN (comp getTitle getAttributes) (comp getAuthor getAttributes)) items))))

Andere Tipps

Ich bin sicher, es ist ein schöner Weg, aber das macht den Job:

(letfn [(get-tag [tag coll] (:content (first (filter #(= tag (:tag %)) coll))))]
  (map #(list (get-tag :c %) (get-tag :e (get-tag :d %)))
       (map :content (:content (clojure.xml/parse "foo.xml")))))

Ergebnisse in

((["ctext1"] ["etext1"]) (["ctext2"] ["etext2"]))
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top