Haco
Haco

Reputation: 55

Lisp data formatting to xml

I'm new to lisp and I can't seem to find any examples of how to format read words from txt file into xml.

example:

tag1
tag2 word2
tag1 word3
tag1 word4

I would like to have exit file: .xml

<tag1>
   <tag2>word2</tag2>
</tag1>
<tag1>word3</tag1>
<tag1>word4</tag1>

or anything similar.

Upvotes: 1

Views: 230

Answers (1)

Vsevolod Dyomkin
Vsevolod Dyomkin

Reputation: 9451

With CXML and SPLIT-SEQUENCE libraries you can do it like this:

(defun write-xml (input-stream output-stream)
  (cxml:with-xml-output
      (cxml:make-character-stream-sink output-stream
                                       :indentation 2 :canonical nil)
    (loop :for line := (read-line input-stream nil) :while line :do
       (destructuring-bind (tag &optional text)
           (split-sequence:split-sequence #\Space line)
         (cxml:with-element tag
           (when text
             (cxml:text text)))))))

The result will be slightly different:

CL-USER> (with-input-from-string (in "tag1
tag2 word2
tag1 word3
tag1 word4")
           (write-xml in *standard-output*))
<?xml version="1.0" encoding="UTF-8"?>
<tag1/>
<tag2>
  word2</tag2>
<tag1>
  word3</tag1>
<tag1>
  word4</tag1>

What you're left with is to figure out how to process nesting of elements in your representation...

Upvotes: 1

Related Questions