×
Namespaces

Variants
Actions

Archived:How to store settings in XML files

From Nokia Developer Wiki
Jump to: navigation, search

Archived.pngAquivado: Este artigo foi arquivado, pois o conteúdo não é mais considerado relevante para se criar soluções comerciais atuais. Se você achar que este artigo ainda é importante, inclua o template {{ForArchiveReview|escreva a sua justificativa}}.

All PySymbian articles have been archived. PySymbian is no longer maintained by Nokia and is not guaranteed to work on more recent Symbian devices. It is not possible to submit apps to Nokia Store.

Article Metadata
Article
Created: lfd (26 Jun 2007)
Last edited: hamishwillee (31 May 2013)

It is possible to store settings in XML files.

This library uses cElementTree. Since PySymbian 1.3.22 it is much faster to load the library! So I advice to upgrade your PySymbian 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()
This page was last modified on 31 May 2013, at 04:09.
55 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×