我很困惑,因为如何通过clojure.contrib的zip-filter.xml访问的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过滤器进行交互.
如果你在这个小例子中发现特别奇怪,请指出.
首先,您应该在您的Fred定义中使用:内容(而不是:内容).
随着这种变化,以下似乎有效:
(-> (zf/xml-> @db :item) ; a convenient way to get to the :item zipper locs first ; but we actually need just one zip/rightmost ; let's move to the rightmost sibling of the first :item ; (which is the last :item in this case) (zip/insert-right fred-item) ; insert Fred to the right zip/root) ; get the modified XML map,; which is the root of the modified zipper
你的append-item2非常相似,只有两个修正:
> zf / xml->返回一系列拉链locs;拉链/右边只接受一个,所以你必须首先钓鱼(因此是上面的第一个);
>完成修改拉链后,您需要使用zip / root来恢复底层树的(修改版本).
作为样式的最后一个注释,print format = printf.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。