我正在为一个简单的项目尝试clojure(第一次)。我需要更新一个给定 csv 文件的 xml 树。我正在逐行读取 csv 文件,提取一些值,循环给定一些值的节点并插入具有另一个值的子节点。
这在我第一次插入项目时工作正常。我第二次得到 NullPointerException (没有痕迹)。我从从 insert-child 获得的返回值中查找根,并将该根节点传递给下一个循环。不知何故,第二次插入在该根元素上失败了。有人知道这里出了什么问题吗?或对此代码的一般反馈,因为这是我第一次尝试编写一些 Clojure。
(require 'clojure.string)
(require '[clojure.java.io :as io])
(require '[clojure.xml :as xml])
(require '[clojure.zip :as zip])
(require '[clojure.data.zip.xml :as zf])
(def business-object-config (xml/parse "BusinessObject.config"))
(def zipped (zip/xml-zip business-object-config ))
(defn sql-table-name [table-name]
(second (re-matches #"(.*?)(Base|ExtensionBase|$)" table-name)))
(defn insert-sqlpropertyname-elem [loc name]
(zip/root (zip/insert-child loc {:tag :SqlPropertyName :content [name]})))
(defn get-entity-node [table-name crm-name business-objects]
(first (zf/xml-> business-objects :Entities
:Entity [:CrmName (zf/text= (clojure.string/lower-case (sql-table-name table-name)))]
:EntityItems
:EntityItem [:CrmPropertyName (zf/text= (clojure.string/lower-case crm-name))])))
(defn process-line [line business-objects]
(let [{crm-name 0 table-name 1 sql-name 6} (clojure.string/split line #";")
node (get-entity-node table-name crm-name business-objects)]
(insert-sqlpropertyname-elem node sql-name)))
(defn process-csv []
(with-open
[rdr (io/reader "input.csv")]
(loop [lines (vec (take 5 (rest (line-seq rdr))))
index (dec (count lines))
boc zipped]
(if (neg? index)
boc
(recur lines (dec index) (process-line (nth lines index) boc))))))
(spit "out.xml" (with-out-str (xml/emit (process-csv)) :pad true))