>>> Down-Translation? <<<

Fredrik Lundh fredrik at pythonware.com
Fri Apr 23 03:17:32 EDT 1999


Nagwa Abdel-Mottaleb <nagwa at math.ephouse.com> wrote:
> I am looking for a suitable language that will enable me to 
> down-translate XML files into something like LaTeX files. 
> Is it easy to use Python for this process? For example, 
> how easy it is to write code segments that enable to 
> translate
> 
> <tag>foo</tag>
> 
> in the xml input file into
> 
> \begin{tag}
> foo
> \end{tag}
> 
> and things like that in the tex output file?
> 
> Any pointers and/or sample code will be appreciated. 
> (Please e-mail me if possible.)

Python comes with an XML parser:
http://www.python.org/doc/lib/module-xmllib.html

here's some code to start with:

---

import sys, xmllib

class myParser(xmllib.XMLParser):

    _eoln = 1

    def __init__(self, out):
        xmllib.XMLParser.__init__(self) # initiate base class
        self.write = out.write
        # for special tags, initiate self.elements here:
        # self.elements = {
        #    "mytag": (self.start_mytag, self.end_mytag)
        # }

    def handle_data(self, data):
        self.write(data)
        self._eoln = (data[:-1] == "\n")

    def unknown_starttag(self, tag, attributes):
        # default is to map tags to begin/end constructs
        if not self._eoln:
            self.write("\n")
        self.write("begin{%s}\n" % tag)
        self._eoln = 1

    def unknown_endtag(self, tag):
        if not self._eoln:
            self.write("\n")
        self.write("end{%s}\n" % tag)
        self._eoln = 1

p = myParser(sys.stdout)
p.feed("<tag>text</tag>")
p.close()

---

</F>





More information about the Python-list mailing list