NMLParser - an XML - object serializer for python

This is the documentation for a Python implementation of a mapping between objects and XML.

The idea is that you can just write your python classes as you would anyway, e.g.:

class Network:    
    def __init__(self):
        self.states = {} 
        self.connections = []
    def addState(self, s):
class State:
    def __init__(self, n=None, c=0): = n
        self.count = c
class Connection:
    def __init__(self, s1=None, s2=None, w=0.0):
        self.s1 = s1
        self.s2 = s2
        self.w = w

... and create an XML schema file (in our peculiar format), to give the generic parser some hints on types of things which are not available from within python space:

<Package name="">
  <Class name="Network">
	<Field name="states" type="list" elementType="State" xmlstyle="hidefield"/>
	<Field name="connections" type="list" elementType="Connection" xmlstyle="hidefield"/>
  <Class name="State">
	<Field name="name" type="string"/>
	<Field name="count" type="int"/>

  <Class name="Connection">
	<Field name="s1" type="ref" elementType="State"/>
	<Field name="s2" type="ref" elementType="State"/>
	<Field name="w" type="double"/>

... and that should be all the work you have to do. To convert object trees to/from XML, use:-

  • First read the schema:-
    netSchema = parseSchemaFile("test-net.sch")
  • Then you can write out an object as xml:-
    print serializeObject(net, netSchema)
  • ... and read in an XML file as an object using:-
    tree = parseXMLFile("test-net.xml", locals(), netSchema)

    ... Here is a sample XML file:-

        <Connection s1="s1" s2="s2" w="0.5"/>
        <Connection s1="s3" s2="s2" w="0.5"/>
        <Connection s1="s2" s2="s3" w="0.5"/>
        <Connection s1="s4" s2="s2" w="0.5"/>
        <State count="100" name="s3"/>
        <State count="100" name="s2"/>
        <State count="100" name="s1"/>
        <State count="100" name="s4"/>