XML parsing and writing

c00i90wn cooldown at gmail.com
Fri Jul 28 14:33:14 EDT 2006


Hey, I'm having a problem with the xml.dom.minidom package, I want to
generate a simple xml for storing configuration variables, for that
purpose I've written the following code, but before pasting it I'll
tell you what my problem is. On first write of the xml everything goes
as it should but on subsequent writes it starts to add more and more
unneeded newlines to it making it hard to read and ugly. Here is the
code that you can test by yourself:

from xml.dom import minidom
import os

class config(object):
  def __init__(self):
    self.xml = os.path.abspath("conf\config.xml")
    if not os.path.isfile(self.xml):
      self.doc = minidom.Document()
      self.__createFile()
    else:
      self.doc = minidom.parse(self.xml)
      self.conf = self.doc.getElementsByTagName("conf")[0]

  def __createFile(self):
    self.conf = self.doc.createElement("conf")
    self.doc.appendChild(self.conf)
    self.write()

  def createNode(self, element, data=False):
    if len(self.conf.getElementsByTagName(str(element))) == 0:
      newNode = self.doc.createElement(str(element))
      self.conf.appendChild(newNode)
    if data: self.nodeData(element, data)

  def nodeData(self, node, data=False):
    try:
      node = self.conf.getElementsByTagName(node)[0]
    except IndexError:
      return
    if data:
      if node.hasChildNodes():
        node.firstChild.replaceWholeText(str(data))
      else:
        data = self.doc.createTextNode(str(data))
        node.appendChild(data)
    else:
      return node.firstChild.data

  def write(self):
    print self.conf.toprettyxml()
    self.doc.writexml(open(self.xml, "w"), addindent = "  ", newl =
"\n", encoding = "utf-8")

if __name__ == "__main__":
  conf = config()
  conf.createNode("path")
  conf.nodeData("path", "somepath")
  print conf.nodeData("path")
  conf.createNode("blah", "foo")
  print conf.nodeData("blah")
  conf.write()




More information about the Python-list mailing list