save configuration information in a global class

Steven Bethard steven.bethard at gmail.com
Mon Mar 28 09:29:46 CEST 2005


Su Wei <pollux.suwei at gmail.com> wrote:
> if i have a xml file like this:
> <ActionMappings>
>     <Action  path="cpuInformation" type="CPUAction" next="CPUFrameGUI"/>
>     <Action path="cdromInformation" type="CDROMAction" next="CDROMFrameGUI"/>
> </ActionMappings>
> 
> i want to save this information,and used by other moduls later.
> 
> how should i do it? ths

First you need an xml library.  There's one built into Python, but
ElementTree is a simpler one: http://effbot.org/zone/element-index.htm

I've saved your text into a file named 'temp.xml':

py> print open('temp.xml').read()
<ActionMappings>
   <Action  path="cpuInformation" type="CPUAction" next="CPUFrameGUI"/>
   <Action path="cdromInformation" type="CDROMAction" next="CDROMFrameGUI"/>
</ActionMappings>

Now let's parse that file:

py> from elementtree import ElementTree
py> actionmappings = ElementTree.parse('temp.xml').getroot()
py> for action in actionmappings:
...     print action.attrib
... 
{'path': 'cpuInformation', 'type': 'CPUAction', 'next': 'CPUFrameGUI'}
{'path': 'cdromInformation', 'type': 'CDROMAction', 'next': 'CDROMFrameGUI'}

Note that I now have an object that I've named 'actionmappings' which
contains all the data I need.  How do you want the information from
the XML file to be available?  If you're happy navigating the XML
structure, you can just pass this object around.  If you included the
code above in a module called, say, 'progconfig', then you could
access this info in another file like:

improt progconfig
# the following should give you 'cpuInformation'
progconfig.actionmappings[0].attrib['path']

If you don't like the format the XML file gives you, you'll need to
give us more information on how you'd like to reformat it.

STeVe

P.S.  Please make sure you reply to the list.  I probably won't be
able to answer again tonight, but someone else on the list may...
-- 
You can wordify anything if you just verb it.
        --- Bucky Katt, Get Fuzzy



More information about the Python-list mailing list