[XML-SIG] XBEL DTD as a meta-dtd

Lars Marius Garshol larsga@ifi.uio.no
18 Sep 1998 11:19:45 +0200


* Andrew M. Kuchling
| 
| Thoughts?  Should there be a way to specific a character range which
| would be escaped numerically, as * or whatever?

I think the xml.util module makes perfect sense, as does the escape
function. I think we'll also eventually want an XMLWriter class to
simplify XML generation as well. I was about to create a module for
myself with these two things anyway.

Here is the escape function I use for element content:

def escape(str):
    return string.replace(string.replace(str,'&',"&amp;"),"<","&lt;")
        
Here is my XMLWriter (note that it is written for data-oriented
documents, not document-like ones):

# A simple XML-generator

import sys,string

class XMLWriter:

    def __init__(self,out=sys.stdout):
        self.out=out
        self.stack=[]

    def doctype(self,root,pubid,sysid):
        if pubid==None:
            self.out.write("<!DOCTYPE %s SYSTEM '%s'>\n" % (root,sysid))
        else:
            self.out.write("<!DOCTYPE %s PUBLIC '%s' '%s'>\n" % (root,pubid,
                                                                 sysid))
        
    def push(self,elem,attrs={}):
        self.__indent()
        self.out.write("<"+elem)
        for (a,v) in attrs.items():
            self.out.write(" %s='%s'" % (a,self.__escape_attr(v))
        self.out.write(">\n")

        self.stack.append(elem)

    def elem(self,elem,content,attrs={}):
        self.__indent()
        self.out.write("<"+elem)
        for (a,v) in attrs.items():
            self.out.write(" %s='%s'" % (a,self.__escape_attr(v))
        self.out.write(">%s</%s>\n" % (self.__escape_cont(content),elem))

    def empty(self,elem,attrs={}):
        self.__indent()
        self.out.write("<"+elem)
        for a in attrs.items():
            self.out.write(" %s='%s'" % a)
        self.out.write("/>\n")
        
    def pop(self):
        elem=self.stack[-1]
        del self.stack[-1]
        self.__indent()
        self.out.write("</%s>\n" % elem)
    
    def __indent(self):
        self.out.write(" "*(len(self.stack)*2))
    
    def __escape_cont(self,str):
        return string.replace(string.replace(str,'&',"&amp;"),"<","&lt;")

    def __escape_attr(self,str):
        str=string.replace(str,'&',"&amp;")
        return string.replace(string.replace(str,"'","&apos;"),"<","&lt;")

--Lars M.