]> git.saurik.com Git - wxWidgets.git/blame - wxPython/samples/ide/activegrid/util/xmlprettyprinter.py
Fix "warning: operation on 'y' may be undefined".
[wxWidgets.git] / wxPython / samples / ide / activegrid / util / xmlprettyprinter.py
CommitLineData
1f780e48
RD
1#----------------------------------------------------------------------------
2# Name: xmlprettyprinter.py
3# Purpose:
4#
5# Author: John Spurling
6#
7# Created: 9/21/04
8# CVS-ID: $Id$
9# Copyright: (c) 2004-2005 ActiveGrid, Inc.
10# License: wxWindows License
11#----------------------------------------------------------------------------
12import xml.sax
2eeaec19 13from activegrid.util.lang import *
1f780e48
RD
14
15class XMLPrettyPrinter(xml.sax.ContentHandler):
16 def __init__(self, indentationChar=' ', newlineChar='\n'):
17 self.xmlOutput = ''
18 self.indentationLevel = 0
19 self.indentationChar = indentationChar
20 self.elementStack = []
21 self.newlineChar = newlineChar
22 self.hitCharData = False
23
24 ## ContentHandler methods
25 def startElement(self, name, attrs):
2eeaec19 26 indentation = self.newlineChar + (self.indentationChar * self.indentationLevel)
1f780e48
RD
27 # build attribute string
28 attrstring = ''
29 for attr in attrs.getNames():
30 value = attrs[attr]
31 attrstring += ' %s="%s"' % (attr, value)
32 self.xmlOutput += '%s<%s%s>' % (indentation, name, attrstring)
33 self.indentationLevel += 1
34 self.elementStack.append(name)
35 self.hitCharData = False
36
37 def characters(self, content):
2eeaec19 38## print "--> characters(%s)" % content
1f780e48
RD
39 self.xmlOutput += content
40 self.hitCharData = True
41
42 def endElement(self, name):
43 self.indentationLevel -= 1
44 indentation = ''
45 if not self.hitCharData:
2eeaec19
RD
46 indentation += self.newlineChar + (self.indentationChar * self.indentationLevel)
47## indentation += self.indentationChar * self.indentationLevel
1f780e48
RD
48 else:
49 self.hitCharData = False
2eeaec19
RD
50## self.xmlOutput += '%s</%s>%s' % (indentation, self.elementStack.pop(), self.newlineChar)
51 self.xmlOutput += '%s</%s>' % (indentation, self.elementStack.pop())
1f780e48
RD
52
53 def getXMLString(self):
54 return self.xmlOutput[1:]
55
56def xmlprettyprint(xmlstr, spaces=4):
57 xpp = XMLPrettyPrinter(indentationChar=' ' * spaces)
58 xml.sax.parseString(xmlstr, xpp)
59 return xpp.getXMLString()
60
2eeaec19 61if isMain(__name__):
1f780e48 62 simpleTestString = """<one>some text<two anattr="booga">two's data</two></one>"""
2eeaec19 63 print xmlprettyprint(simpleTestString)
1f780e48 64