9

我很困惑如何习惯性地更改通过 clojure.contrib 的 zip-filter.xml 访问的 xml 树。应该尝试这样做,还是有更好的方法?

假设我有一些像这样的虚拟 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-filter 交互。

如果您在这个小示例中发现任何特别奇怪的地方,请指出。

4

2 回答 2

8

首先,您应该在 Fred 的定义中使用:content(而不是:contents)。

随着这种变化的发生,以下似乎可行:

(-> (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的非常相似,只需进行两个更正:

  1. zf/xml->返回一个 zipper locs 序列;zip/rightmost只接受一个,所以你必须先钓出一个(因此first在上面);

  2. 修改完拉链后,您需要使用zip/root回到底层树(的修改版本)。

作为风格的最后一点,print+ format= printf。:-)

于 2010-05-20T17:40:59.677 回答
5

在 create-item 中,您为 :content 输入了错误的 :contents ,并且您应该更喜欢向量而不是文字列表。

(我打算做一个更全面的答案,但 Michal 已经写了一个很好的答案。)

zip-filter 的替代方法是 Enlive:

(require '[net.cgrand.enlive-html :as e]) ;' <- fix SO colorizer

(def db (ref (-> "itemdb.xml" java.io.File. e/xml-resource))

(defn create-item [name desc]
  {:tag :item
   :attrs {:id "3"}
   :content [{:tag :name :attrs {} :content [name]}
             {:tag :desc :attrs {} :content [desc]}]})

(def fred-item (create-item "Fred" "Green-haired astrophysicist."))

(dosync (alter db (e/transformation [:itemlist] (e/append fred-item))))
于 2010-05-20T18:00:38.527 回答