我很困惑,因爲如何通過clojure.contrib的zip-filter.xml來習慣性地更改xml樹。應該試圖做到這一點,還是有更好的方法?在Clojure中的XML文件中插入到Zipper樹中
說,我有一些虛擬的xml文件 「itemdb.xml」 是這樣的:
<itemlist>
<item id="1">
<name>John</name>
<desc>Works near here.</desc>
</item>
<item id="2">
<name>Sally</name>
<desc>Owner of pet store.</desc>
</item>
</itemlist>
而且我有一些代碼:
(require '[clojure.zip :as zip]
'[clojure.contrib.duck-streams :as ds]
'[clojure.contrib.lazy-xml :as lxml]
'[clojure.contrib.zip-filter.xml :as zf])
(def db (ref (zip/xml-zip (lxml/parse-trim (java.io.File. "itemdb.xml")))))
;; Test that we can traverse and parse.
(doall (map #(print (format "%10s: %s\n"
(apply str (zf/xml-> % :name zf/text))
(apply str (zf/xml-> % :desc zf/text))))
(zf/xml-> @db :item)))
;; I assume something like this is needed to make the xml tags
(defn create-item [name desc]
{:tag :item
:attrs {:id "3"}
:contents
(list {:tag :name :attrs {} :contents (list name)}
{:tag :desc :attrs {} :contents (list desc)})})
(def fred-item (create-item "Fred" "Green-haired astrophysicist."))
;; This disturbs the structure somehow
(defn append-item [xmldb item]
(zip/insert-right (-> xmldb zip/down zip/rightmost) item))
;; I want to do something more like this
(defn append-item2 [xmldb item]
(zip/insert-right (zip/rightmost (zf/xml-> xmldb :item)) item))
(dosync (alter db append-item2 fred-item))
;; Save this simple xml file with some added stuff.
(ds/spit "appended-itemdb.xml"
(with-out-str (lxml/emit (zip/root @db) :pad true)))
我不清楚如何使用Clojure的。 zip在這種情況下適當地運作,以及如何與zip-過濾器交互。
如果您在這個小例子中發現任何特別怪異的東西,請指出。
的contrib.zip過濾器.xml現在轉移到https://github.com/clojure/data.zip/ – claj 2013-08-17 10:56:14