Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

SXPathまじやばい

みずぴー日記:E4Xまじやばいに対抗して、GaucheでSXPathを使ってみる。

SXML要素を作る

(use sxml.ssax)
(use sxml.sxpath)

(define sxml (call-with-input-string "<product>
                                        <model stock=\"yes\">
                                          <name>foo</name>
                                           <price>100</price>
                                        </model>
                                        <model stock=\"no\">
                                           <name>bar</name>
                                           <price>200</price>
                                        </model>
                                      </product>"
	       (cut ssax:xml->sxml <> '())))

子ノードへのアクセス

((sxpath "/product/model/name/text()") sxml)

==> ("foo" "bar")

属性へのアクセス

((sxpath "/product//@stock[1]/text()") sxml)

==> ("yes")

子孫ノードへのアクセス

((sxpath "//name/text()") sxml)

==> ("foo" "bar")

条件式をSchemeで書く (price < 150 の model)

((sxpath `(// (model (,(lambda (node root vars)
			 ((sxml:filter
			   (lambda (n)
			     (> 150 (sxml:number ((sxpath "/price") n)))))
			  node)))))) sxml)

==> ((model (|@| (stock "yes")) (name "foo") (price "100")))

条件式をSchemeで書く (name が正規表現で#/ar/にマッチする model)

((sxpath `(// (model (,(lambda (node root vars)
			 ((sxml:filter
			   (lambda (n)
			     (#/ar/ (sxml:string ((sxpath "/name") n)))))
			  node)))))) sxml)

==> ((model (|@| (stock "no")) (name "bar") (price "200")))