from PyXML import * from string import * import sys import types class Pcdata: def __init__(self, value, where=None): self.value = value self.where = where def printme(self, file): Print(file, self.value) class Attribute: def __init__(self, name, value, spec=None, uri=None, local=None): self.name = name self.value = value self.spec = None def printme(self, file): # XXX escape relevant chars! if self.value: PrintTextLiteral(file, " %s='%s'" % (self.name, self.value)) class Element: def __init__(self, arg1, arg2=None, arg3=None): self.attrs = {} self.nsattrs = {} self.children = [] if type(arg1) == types.StringType: self.fromString(arg1) elif type(arg1) == BitType: self.fromBit(arg1, arg2, arg3) elif type(arg1) == ItemType: self.fromItem(arg1, arg2) elif type(arg1) == FileType: self.fromFile(arg1, arg2) def fromString(self, name): self.name = name self.spec = None self.local = None self.uri = None return def fromBit(self, bit, file, where): doctype = file.doctype if doctype.elementTypes.has_key(bit.label): self.spec = doctype.elementTypes[bit.label] else: self.spec = None self.name = bit.label self.local = bit.llabel self.uri = bit.nsuri self.getAttrs(bit.item) self.where = where if bit.type == "empty": if where: self.where2 = file.where else: self.where2 = None return if where: w = file.where else: w = None b = GetNextBit(file) while b.type != "end": if b.type == error: raise Exception, "parse error" if b.type == "start" or b.type == "empty": self.children.append(Element(b, file, w)) elif b.type == "text": self.children.append(Pcdata(b.body, w)) if where: w = file.where b = GetNextBit(file) self.where2 = w return def fromItem(self, item, doctype): if doctype.elementTypes.has_key(item.label): self.spec = doctype.elementTypes[item.label] else: self.spec = None self.name = item.label self.local = item.llabel self.uri = item.nsuri self.getAttrs(item) for child in item.data: if type(child) == ItemType: self.children.append(Element(child, doctype)) else: self.children.append(Pcdata(child)) def fromFile(self, file, notewhere): if notewhere: w = file.where else: w = None b = GetNextBit(file) while b.type != "start" and b.type != "empty": if b.type == error: raise Exception, "parse error" if notewhere: w = file.where b = GetNextBit(file) self.fromBit(b, file, w) def getAttrs(self, item): atts = ItemActualAttributesNS(item) for (name,value,uri,local) in atts: if self.spec: a = Attribute(name, value, self.spec.attrDefns[name], uri, local) else: a = self.attrs[name] = Attribute(name, value, None, uri, local) self.attrs[name] = a self.nsattrs[(uri,local)] = a def printme(self, file): PrintTextLiteral(file, "<%s" % self.name) for attr in self.attrs.values(): attr.printme(file) PrintTextLiteral(file, ">") for child in self.children: child.printme(file) PrintTextLiteral(file, "" % self.name)