from xml.dom import minidom
from os.path import join, exists
from os import mkdir
import re
class Settings:
"""
Settings Class
For reading and writting XML Files to hold the settings for scripts
Coded by Donno
"""
settingVer = 1.0
scriptTitle = ""
filename = ""
settings = {}
def __init__(self,filename,scriptTitle):
self.scriptTitle = scriptTitle
self.filename = filename
self.load()
def load(self):
filepath = join("P:\\","script_settings", self.filename)
if exists(filepath):
try:
xmldoc = minidom.parse(filepath)
xmlsettings = xmldoc.getElementsByTagName("settings")[0]
except:
self.create()
return
"""
For this to be great xml would need to be in form <setting name="username">hello</setting>
Because then xmldoc.getElementsByTagName("setting") would be possible then you use getAttribute to crap the name of the setting 'username'
SO USE REGEXP unless I (Donno) decide to write a hack my self or change the formatting, or unless someone else wants to write the
hack to get it working <username>donno</username> to be read
"""
data = xmlsettings.toxml()
regp = '<([^<]*)>([^</]*)</'
save_info = re.compile(regp,re.IGNORECASE).findall(data)
for x in save_info:
self.settings[x[0]] = x[1].strip()
print self.settings
else:
self.create()
def create(self):
filepath = join("P:\\","script_settings", self.filename)
if not exists(filepath):
self.saveXMLfromArray()
def setDefaultSettings(self):
self.settings = {"usernane": "donno","something": "true"}
def saveXMLfromArray(self):
"""
saveXMLfromArray
Creates a dom Document of the settings array and saves it to the xml
"""
self.setDefaultSettings()
# File doesn't exist so create it
xmldoc = minidom.Document()
# Create the <settings> base element
settingElem = xmldoc.createElement("settings")
settingElem.setAttribute("setting-version", str(self.settingVer))
settingElem.setAttribute("name", self.scriptTitle)
xmldoc.appendChild(settingElem)
# Create a element for each setting with the textnode as the value
for key in self.settings:
newElem = xmldoc.createElement(key)
newElem.appendChild(xmldoc.createTextNode(self.settings[key]))
settingElem.appendChild(newElem)
self.save(xmldoc)
def save(self,xmldoc):
"""
This function takes a xml Document object and saves it to XML
"""
filepath = join("P:\\","script_settings", self.filename)
if not exists(join("P:\\","script_settings")):
mkdir(join("P:\\","script_settings"))
fsock = open(filepath,"w")
fsock.write(xmldoc.toprettyxml(indent=" "))
fsock.close()