2007/11/24

Common Lisp で XML をいじる

Closure XML Parser http://common-lisp.net/project/cxml/ を使って XML をいじってみます。


準備


CVS で最新バージョンを取得します。


cvs -d :pserver:anonymous:anonymous@common-lisp.net:/project/cxml/cvsroot co cxml
cvs -d :pserver:anonymous:anonymous@common-lisp.net:/project/cxml/cvsroot co closure-common

いつもの手順で asdf:*central-registry* に登録します。


Quick Start


まずは require です。


(require :cxml)

お試し用の XML ファイルを作成します。


(with-open-file (out "/tmp/try.xml" :direction :output
:element-type '(unsigned-byte 8)
:if-exists :supersede)
(cxml:with-xml-output
(cxml:make-octet-stream-sink out :indentation 2 :canonical nil)
(cxml:with-element "try"
(cxml:attribute "title" "XML")
(cxml:with-element "para"
(cxml:text "試してみよう。")))))

DOM でいじってみます。


(let* ((builder (cxml-dom:make-dom-builder)) ;DOM ビルダーを作る
(dom (cxml:parse-file "/tmp/try.xml" builder)) ;パースする
(try-element (dom:document-element dom))) ;エレメントを取得
(format t "DOM オブジェクト: ~a~%" dom)
(format t "try タグ(~a)のタグ名: ~a, title属性の値: ~a~%"
try-element
(dom:tag-name try-element) ;タグ名を取得
(dom:get-attribute try-element "title"))) ;属性値を取得

リストでいじってみます。


リストから XML ファイルを出力します。


(with-open-file (out "/tmp/try.xml" :direction :output
:element-type '(unsigned-byte 8)
:if-exists :supersede)
(cxml-xmls:map-node (cxml:make-octet-stream-sink out)
'("try" (("title" "XML")) ("para" nil "リストから出力。"))
:include-namespace-uri nil))

XML から リストを取得します。


(cxml:parse-file "/tmp/try.xml" (cxml-xmls:make-xmls-builder))
;; => ("try" (("title" "XML")) ("para" NIL "リストから出力。"))

0 件のコメント: