Tôi đang bối rối như thế nào để thay đổi thành phần một cây xml được truy cập thông qua tệp zip-filter.xml của clojure.contrib. Nên cố gắng để làm điều này ở tất cả, hoặc là có một cách tốt hơn?Chèn vào cây Zipper trên các tệp XML trong Clojure
Nói rằng tôi có một số giả tập tin xml "itemdb.xml" như thế này:
<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>
Và tôi có một số mã:
(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)))
Tôi không rõ về cách sử dụng các clojure. các hàm zip thích hợp trong trường hợp này và cách tương tác với bộ lọc zip.
Nếu bạn phát hiện ra bất kỳ điều gì đặc biệt kỳ lạ trong ví dụ nhỏ này, vui lòng chỉ ra.
các contrib.zip lọc .xml hiện được chuyển đến https://github.com/clojure/data.zip/ – claj