在Clojure中,我如何遍历XML数据结构并将包含特殊字符的所有文本内容包装为CDATA标记?
例如,以下XML:
<root>
<child>no special characters</child>
<child>special characters &</child>
<parent>
<child>special characters ></child>
</parent>
</root>
应该成为
<root>
<child>no special characters</child>
<child><![CDATA[special characters &]]></child>
<parent>
<child><![CDATA[special characters >]]></child>
</parent>
</root>
答案 0 :(得分:1)
以下内容包含CDATA中包含<
,>
或&
的文本节点。使用clojure.data.xml 0.0.7:
(require '[clojure.data.xml :as xml] '[clojure.zip :as zip])
;; as in the question text:
(def test-xml
"<root>
<child>no special characters</child>
<child>special characters &</child>
<parent>
<child>special characters ></child>
</parent>
</root>")
(def x (xml/parse-str test-xml))
(def z (zip/xml-zip x))
(defn contains-special-chars? [s]
(.find (re-matcher #"[<>&]" s)))
(loop [z z]
(if (zip/end? z)
(-> z zip/root xml/emit-str)
(let [n (zip/node z)]
(if (string? n)
(if (contains-special-chars? n)
(recur (zip/edit z xml/->CData))
(recur (zip/next z)))
(recur (zip/next z))))))