1

Clojure では、XML データ構造をトラバースし、特殊文字を含むすべてのテキスト コンテンツを CDATA タグでラップするにはどうすればよいでしょうか?

たとえば、次の XML:

<root>
  <child>no special characters</child>
  <child>special characters &amp;</child>
  <parent>
    <child>special characters &gt;</child>
  </parent>
</root>

なるべき

<root>
  <child>no special characters</child>
  <child><![CDATA[special characters &]]></child>
  <parent>
    <child><![CDATA[special characters >]]></child>
  </parent>
</root>
4

1 に答える 1

1

<以下は、>またはを含むテキスト ノードを&CDATA にラップします。Clojure 1.5.1 REPL で 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 &amp;</child>
     <parent>
       <child>special characters &gt;</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))))))
于 2013-05-24T01:26:25.187 に答える