September 10, 2014

How to Manipualte XML in Python with the Standard Library

Just added tests and removed all dependencies to the XML serialiser:

from collections import OrderedDict
import cStringIO as StringIO
import logging
from xml import sax

logging.basicConfig(level=logging.FATAL)

class ContentHandler(sax.ContentHandler):
    def __init__(self):
       sax.ContentHandler.__init__(self)
       self.dictionary = {}

    def startElement(self, qname, attrs):
        if qname == 'element':
            self.dictionary[attrs.getValue('key')] = attrs.getValue('value')

def loads(__xml):
    """ 
        restores xml as a dict, without the  declaration
    """
    ch = ContentHandler()
    sax.parseString(__xml, ch)
    return(ch.dictionary)

def load(file_):
    __xml = None
    with open(file_) as fin:
        __xml = loads(fin.read())
    return(__xml)

def dumps(obj):
    """
       Dumps obj to XML
    """
    logging.debug(obj)
    __xml = ''
    for k in obj.keys():
        __xml = __xml +''.format(k, obj[k])
    return('{}'.format(__xml))

def dump(obj, output):
    __bytes = dumps(obj)
    logging.debug(__bytes)
    with open(output, 'w') as fout:
        fout.write(__bytes)
    return(fout.name)

if __name__ == '__main__':
    dictionary = {'1':'True', '0' : 'False'}
    xml__ = dumps(dictionary)
    print('PASSED deserialisation'
    logging.debug(xml__)
    if loads(xml__) == dictionary:
        print 'PASSED serialisation'
    else:
        print 'FAILED serialisation'

What's the XML that comes out look like? Take a look, under the hood:

<root><element key="1" value="True"/><element key="0" value="False"/></root>

No comments:

Post a Comment