view ide/project.py @ 7:2db4d2b362e6

Added xml project
author windel
date Sat, 15 Oct 2011 10:03:21 +0200
parents
children edd70006d3e4
line wrap: on
line source

"""
 Project that can be stored to and loaded from XML.
"""

from xml.sax import ContentHandler, make_parser
import xml.dom.minidom as md
import os.path

class ProjectContentHandler(ContentHandler):
   def __init__(self, project):
      self.project =  project
      self.inFiles = False
   def startElement(self, name, attrs):
      if name == 'Project':
         self.project.name = attrs['name']
      if name == 'Files':
         self.inFiles = True
      if name == 'File' and self.inFiles:
         self.project.files.append(attrs['Filename'])
   def endElement(self, name):
      if name == 'Files':
         self.inFiles = False

class Project:
   def __init__(self):
      self.name = ""
      self.files = []
      self.settings = {}

   def save(self, filename):
      """ Save the project in XML format """
      # Create document:
      doc = md.Document()
      # Add project:
      project = doc.createElement("Project")
      project.setAttribute("name", self.name)
      doc.appendChild(project)

      # Add project files:
      filesNode = doc.createElement("Files")
      project.appendChild(filesNode)
      for f in self.files:
         fe = doc.createElement("File")
         fe.setAttribute("Filename", f)
         filesNode.appendChild(fe)

      # Write the XML file:
      xml = doc.toprettyxml()
      with open(filename, 'w') as f:
         f.write(xml)

   def load(self, filename):
      """ Load the project from the XML file """
      if not os.path.exists(filename):
         return
      parser = make_parser()
      handler = ProjectContentHandler(self)
      parser.setContentHandler(handler)
      parser.parse(filename)