XML文章のツリーを構築する:cxml stp - lisp-cookbook-ja/common-lisp GitHub Wiki
- XMLデータからSTPツリーを作る
Closure XMLのcxml:parseを使います。
;; ファイルからXMLデータを読み込んでSTPツリーを作る
(cxml:parse #p"data.xml" (stp:make-builder))
;; 文字列からSTPツリーを作る
(cxml:parse "<element>content</element>" (stp:make-builder))
;; :element-typeが(unsigned-byte 8)のストリームからXMLデータを読み込んでSTPツリーを作る
(cxml:parse octet-stream (stp:make-builder))
APIを使って一からSTPツリーを組み立てることもできます。
(defparameter *tips-cl*
(let* ((ns "http://tips.lisp-users.org/common-lisp") ; 名前空間
(e (stp:make-element "root" ns)) ; ルート要素
(a (stp:make-attribute "attribute" "sample")) ; ルート要素に設定する属性
(child-1 (stp:make-element "child1" ns)) ; 子要素
(child-2 (stp:make-element "child2" ns)) ) ; もうひとつの子要素
(stp:append-child child-1 (stp:make-text "sample1")) ; 子要素の内容を設定
(stp:append-child child-2 (stp:make-text "sample2")) ; 同上
(stp:add-attribute e a) ; ルート要素に属性を設定
(stp:append-child e child-1) ; ルート要素に子要素を追加
(stp:append-child e child-2) ; 同上
(stp:make-document e))) ; ルート要素をもとにXMLデータを生成
ちゃんと組み立てられたかどうか、文字列として出力してみましょう。
(stp:serialize *tips-cl* (cxml:make-string-sink))
;=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
; <root xmlns=\"http://tips.lisp-users.org/common-lisp\" sample=\"att\"><child1>sample1</child1><child2>sample2</child2></root>"