Translating S-expressions into XML
updated: 2007-01-08
newLISP has built in support for parseing XML into s-expressions using xml-parse, but going the other way translating s-expressions into XML has to be coded. Fortunately this is a natural task for LISP with a recursive algorithm. The following function can be used to translate a LISP s-expression back into XML (syntax highlighted version here ):
;; translate s-expr to XML
;;
(define (expr2xml expr (level 0))
(cond
((or (atom? expr) (quote? expr))
(print (dup " " level))
(println expr))
((list? (first expr))
(expr2xml (first expr) (+ level 1))
(dolist (s (rest expr)) (expr2xml s (+ level 1))))
((symbol? (first expr))
(print (dup " " level))
(println "<" (first expr) ">")
(dolist (s (rest expr)) (expr2xml s (+ level 1)))
(print (dup " " level))
(println "</" (first expr) ">"))
(true
(print (dup " " level)
(println "<error>" (string expr) "<error>")))
))
;; a lisp expression for a person
(set 'expr '(person
(name "John Doe")
(address (street "Main Street") (city "Anytown"))))
;; translate to XML with default indentation 0
(expr2xml expr) =>
<person>
<name>
John Doe
</name>
<address>
<street>
Main Street
</street>
<city>
Anytown
</city>
</address>
</person>
The second parameter 0 is the indentation level for the outermost tag expression.