You Are Here:

Community: Wiki

This page was last modified on 17 November 2009, at 09:33.

How to store settings in XML files

From Forum Nokia Wiki

It is possible to store settings in XML files.

This library uses cElementTree. Since PyS60 1.3.22 it is much faster to load the library! So I advice to upgrade your PyS60 installation if you haven't done it yet.

The library

# imports.
try:
from cElementTree import ElementTree, XMLTreeBuilder
except:
import sys
sys.exit("cElementTree module is not installed!")
 
import urllib, os.path
 
## XML Parser used with the framework.
class MParser( ElementTree ):
## The constructor.
# @param self The object pointer.
def __init__( self ):
ElementTree.__init__( self )
 
## Download the xml file at the given url (@a aUrl), read it, create and
# return an xml tree object from the data string.
# @param self The object pointer.
# @param aUrl xml file url to downloaded and parsed.
def fromurl( self, aUrl ):
# urlopen return file object
ressource = urllib.urlopen( aUrl )
string = ressource.read( )
return self.fromstring( string )
 
## Create an xml tree object from a string.
# @param self The object pointer.
# @param aString The string to be parsed by XMLTreeBuilder in order to
# create an xml tree object.
def fromstring( self, aString ):
parser = XMLTreeBuilder( )
parser.feed( aString )
return parser.close( )
 
## Create an xml tree object from a file.
# @param self The object pointer.
# @param aFilePath The file path to be parsed in order to create an xml
# tree object.
def fromfile( self, aFilePath ):
self.parse( aFilePath )
return self.getroot( )
 
## Parse a xml object to its string representation.
# @param self The object pointer.
# @param aElement Element to be parsed.
# @param aEncoding Encoding to use for the string.
def tostring( self, aElement, aEncoding=None ):
class dummy:
pass
data = []
file = dummy( )
file.write = data.append
ElementTree( aElement ).write( file, aEncoding )
return "".join( data )
 
 
## Setting class used with the framework.
class Settings( object, MParser ):
## The default file schemas to write in the settings file.
_iDefaultSchemas = """
<?xml version="1.0" encoding="UTF-8"?>
<settings>
<host>server.xxx</host>
<port>80</port>
<imagedir>D:\\AppDirectory\\</imagedir>
</settings>
"""

## Key dictionnary containing the settings options.
_iKeys = {}
 
## file header.
_iFileHeader = u'<?xml version="1.0" encoding="UTF-8"?>'
 
## Parent tag key.
_iRootTag = u'settings'
 
## The constructor.
# @param self The object pointer.
# @param aFile A settings file path.
# @param aSchemas If given, XML to write in the settings file if empty and
# or has to be created.
def __init__( self, aFile, aSchemas=None ):
if os.path.splitext( aFile )[1].lower( ) != ".xml":
sys.exit( "XML files expected" )
 
## File path.
self._iFile = aFile
# set default structure if given.
if aSchemas:
self._iDefaultSchemas = aSchemas
# get the last config from the file.
self._readSettings( )
 
 
## Set a new option on the settings file.
# @param self The object pointer.
# @param aOption New option to add.
# @param aValue Value to set for the option.
def set( self, aOption, aValue ):
# set the given key.
self._iKeys[aOption] = aValue
# write in the settings file.
self._writeSettings( )
 
## Get options on the settings file.
# @param self The object pointer.
# @param aOption If an option is given, the method will return its value
# or None if it doesn't exist. If no options given, the method returns the
# entire dictionnary.
def get( self, aOption=None ):
try:
if aOption:
return self._iKeys[aOption]
else:
return self._iKeys
except:
return None
 
## Set a new option on the settings file.
# @param self The object pointer.
# @param aOption Key to remove.
def remove( self, aOption ):
# set the given key.
del self._iKeys[aOption]
# write in the settings file.
self._writeSettings( )
 
## Read the settings from the settings file.
# @param self The object pointer.
def _readSettings( self ):
# needed variable.
root = None
 
# next node.
def nextNode( aParent ):
elements = {}
dict = None
for node in parent:
if len(node) != 0:
tag, dict = next_node( node )
elements[tag] = dict
else:
elements[node.tag] = node.text
return parent.tag, elements
 
# if the file exists, we read it.
if os.path.isfile( self._iFile ) and os.path.exists( self._iFile ):
root = self.fromfile( self._iFile )
# if not we create it and write _iDefaultSchemas inside.
else:
rs = open( self._iFile, 'w' )
rs.writelines( self._iDefaultSchemas.strip( ) )
rs.close( )
root = self.fromstring( self._iDefaultSchemas.strip( ) )
 
for node in root:
if len( node ) != 0:
tag, dict = nextNode( node )
self._iKeys[tag] = dict
else:
self._iKeys[node.tag] = node.text
 
 
 
## Write the settings into the settings file.
# @param self The object pointer.
def _writeSettings( self ):
rs = open( self._iFile, 'w' )
rs.write( self._iFileHeader+'\n' )
rs.write( u'<'+self._iRootTag+'>'+'\n' )
for key in self._iKeys:
if self._iKeys[key]:
rs.write( " <"+key+">"+self._iKeys[key]+"</"+key+">"+'\n' )
else:
rs.write( " <"+key+"></"+key+">"+'\n' )
 
rs.write( u'</'+self._iRootTag+'>'+'\n' )
rs.close( )


Usage

# creates test.xml in the memory drive.
config = Settings( "E:\\Others\\test.xml" )
 
# print all key.
print config.get()
 
# set some key.
config.set('uid', 'blablabla')
config.set('uname', 'LFDM')
 
# print all key.
print config.get()
 
# print only uid.
print 'uid is: ', config.get('uid')
 
# remove uname key.
config.remove('uname')
 
# print all keys.
print config.get()

Related Wiki Articles

No related wiki articles found

Rate This

 
Bookmark this page: DeliciousDiggFacebookGoogleYahooStumbleUponRedditDiigoTechnocratiTwitter  Share this page Share this page Print this Page Print this page Invite a friend Invite a friend
京ICP备05048969号    Email Newsletters Press Terms & Conditions Privacy Policy Sitemap Contact Us © 2009 Nokia 
RDF Facets: qdcZidentifierQSxhttpE3aE2fE2fwikiE2eforumE2enokiaE2ecomE2findeE78E2ephpE2fHowE5ftoE5fuseE5ffontsE5finE5fPythonX qdcZtypeQUqfnZE45E78cludedFromGeneralE4cistingsQ qdcZtypeQUqfntypeZCommunityContentQ qdcZtypeQUqfntypeZE52esourceQ qdcZtypeQUqfntypeZWebpageQ qdcZtypeQUqfntypeZWikiContentQ qdcZtypeQUqmarsZManagedE52esourceQ qdcZtypeQUqwebZInformationE52esourceQ qdcZtypeQUqwebZPageQ qdcZtypeQUqwebZE52esourceQ qdcZtypeQUqrdfsZE52esourceQ qfnZtopicQUqfnTopicZpythonQ qfnZtopicQUqfnTopicZseriesE5f60Q qfnZtypeQUqfntypeZCommunityContentQ qfnZtypeQUqfntypeZE52esourceQ qfnZtypeQUqfntypeZWebpageQ qfnZtypeQUqfntypeZWikiContentQ qfnZuserE5ftagQSxpythonX qfnZuserE5ftagQSxs60X qmarsZlanguageQUxhttpE3aE2fE2fswE2enokiaE2ecomE2flanguageE2d1E2fenX qrdfZtypeQUqfnZE45E78cludedFromGeneralE4cistingsQ qrdfZtypeQUqfntypeZCommunityContentQ qrdfZtypeQUqfntypeZE52esourceQ qrdfZtypeQUqfntypeZWebpageQ qrdfZtypeQUqfntypeZWikiContentQ qrdfZtypeQUqmarsZManagedE52esourceQ qrdfZtypeQUqwebZInformationE52esourceQ qrdfZtypeQUqwebZPageQ qrdfZtypeQUqwebZE52esourceQ qrdfZtypeQUqrdfsZE52esourceQ