For general information on reading an XML file in Python,
see Python XML processing with lxml. Note that the et.parse()
function may raise either of two exceptions. If the file
is unreadable, it will raise IOError. If
the file is readable but not well-formed, it raises
et.XMLSyntaxError.
# - - - R e p o r t I n f o . _ _ i n i t _ _ - - -
def __init__ ( self, fileName ):
'''Constructor for ReportInfo.'''
#-- 1 --
# [ if fileName names a readable, well-formed XML file ->
# doc := that file as an et.ElementTree
# else -> raise IOError ]
try:
doc = et.parse ( fileName )
except et.XMLSyntaxError, detail:
raise IOError, ( "Can't read the report parameters "
"file '%s': %s" % (fileName, detail) )
To find all the ROOM_N nodes in
the document, we can use the XPath expression
“//room”. The
resulting node set is converted into a set
of entries in self.roomMap
by Section 27.2, “ReportInfo.__buildRooms():
Build the room dictionary”.
#-- 2 --
# [ roomNodeSet := all room nodes in doc ]
roomNodeSet = doc.xpath ( '//%s' % ROOM_N )
#-- 3 --
# [ self.roomMap := as invariant, with data taken from
# roomNodeSet ]
self.__buildRooms ( roomNodeSet )
Similar techniques find all the SYSTEM_N nodes, and use those
nodes to set up self.systemMap.
See Section 27.3, “ReportInfo.__buildSystems():
Build the system map”.
#-- 4 --
# [ systemNodeSet := all system nodes in doc ]
systemNodeSet = doc.xpath ( '//%s' % SYSTEM_N )
#-- 5 --
# [ self.systemMap := as invariant, with data taken
# from systemNodeSet ]
self.__buildSystems ( systemNodeSet )
Finally, we go through the list of device classes
and build self.deviceList.
#-- 6 --
# [ deviceNodeSet := all device nodes in doc ]
deviceNodeSet = doc.xpath ( '//%s' % DEVICE_N )
#-- 7 --
# [ self.deviceList := as invariant, with data taken
# from deviceNodeSet ]
self.deviceList = [ node.attrib [ KIND_A ]
for node in deviceNodeSet ]