[s-xml-devel] xpath extras

Andy Chambers achambers.home at googlemail.com
Fri Feb 22 10:36:21 UTC 2008


Hi,

In the course of using my little xpath contribution, I've come up with a few
macros that make life easier.


(defmacro ?> (xpath doc)
  "Execute the specified xpath on doc.  If the result is a list of length 1,
make it an atom.
  `(let ((rslt (funcall (sxpath ,xpath) ,doc)))
     (if (second rslt)
         rslt
         (car rslt))))

(defmacro ?let (bindings &body body)
  "Bind names to xpaths in bindings.  Each name then refers to a function
that takes as its
argument an sxml node and returns the result of executing the specified
xpath on that node"
  (with-gensyms (doc)
    `(labels ,(loop for (name xpath) in bindings
                  collect `(,name (,doc)
                                   (?> ,xpath ,doc)))
       , at body)))

(defmacro with-attrs (bindings node &body body)
  "Convenience function to make the specified attributes available.  Works
like with-accessors
but for xml attributes"
  `(let ,(loop for (name attr) in bindings
            collect `(,name (cadr (?> '(:@ ,attr) ,node))))
     , at body))

;; Note that the second one requires the macro `with-gensyms' (included
below for convenience)

(defmacro with-gensyms ((&rest names) &body body)
  `(let ,(loop for n in names collect `(,n (gensym)))
     , at body))


;;
;Andy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mailman.common-lisp.net/pipermail/s-xml-devel/attachments/20080222/05ae7bb7/attachment.html>


More information about the s-xml-devel mailing list