|
class xmlobj(xml):
"""Implements a record object on top of the XML object. Primarily this has to do with
the organization of field values, which are normally <field]] attributes (but needn't be.)
"""
def __init__ (self, defn=None, str=None, xml=None, cmd=None):
"""Create XML object from optional string input"""
self._list = defn
try:
self._xml = xml._xml
except:
self._xml = xml
if cmd:
str = None
self.parse_cmdline (cmd)
if str:
try:
self.parse (str)
except ParseError, message:
raise ParseError, message
# --------------------------------------------------------------
# Getting and setting the value of the list definition.
# --------------------------------------------------------------
def define (self, list):
self._list = list
def defn (self):
return self._list
# --------------------------------------------------------------
# Field reading.
# --------------------------------------------------------------
def __getitem__ (self, key):
if self._xml == None: return ""
return xmlapi.xmlobj_get (self._xml, self._list, key)
def get (self, field):
if self._xml == None: return ""
return xmlapi.xmlobj_get (self._xml, self._list, key)
def key (self):
if self._xml == None: return ""
return xmlapi.xmlobj_getkey (self._xml, self._list)
# --------------------------------------------------------------
# Field writing. Note that we can choose element or field storage.
# --------------------------------------------------------------
def __setitem__ (self, key, value):
if self._xml == None: self._xml = xmlapi.xml_create ("record")
try:
xmlapi.xmlobj_set (self._xml, self._list, key, value)
except:
xmlapi.xmlobj_set (self._xml, self._list, key, `value`)
def set (self, key, value):
if self._xml == None: self._xml = xmlapi.xml_create ("record")
try:
xmlapi.xmlobj_set (self._xml, self._list, key, value)
except:
xmlapi.xmlobj_set (self._xml, self._list, key, `value`)
def set_elem (self, key, value):
if self._xml == None: self._xml = xmlapi.xml_create ("record")
xmlapi.xmlobj_set_elem (self._xml, self._list, key, value)
# -------------------------------------------------------------
# Formatting a record into a string using the square-bracket notation
# -------------------------------------------------------------
def format (self, format):
if self._xml == None: self._xml = xmlapi.xml_create ("record")
return xmlapi.xmlobj_format (self._xml, self._list, format)
def parse_cmdline (self, str): # TODO: move this into C! And make it not suck!
cmdlist = split(str)
cmd = cmdlist[0]
args = []
curarg = ''
for a in cmdlist[1:]:
if curarg != '':
curarg = curarg + ' ' + a
if a[-1] == '"':
args.append (curarg[:-1])
curarg = ''
else:
if a[0] == '"':
curarg = a[1:]
else:
args.append (a)
if curarg != '': args.append (curarg)
self.parse ('<action command="%s" parms="%d"/>' % (cmd, len(args)))
for parm in args:
p = xmlapi.xml_create('parm')
xmlapi.xml_append(p, xmlapi.xml_createtext(parm))
xmlapi.xml_append_pretty (self._xml, p)
|