]> git.saurik.com Git - wxWidgets.git/blob - wxPython/samples/ide/activegrid/util/xmlprettyprinter.py
Applied patch [ 1284335 ] doc update for wxString::operator[]
[wxWidgets.git] / wxPython / samples / ide / activegrid / util / xmlprettyprinter.py
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 #----------------------------------------------------------------------------
12 import xml.sax
13 from activegrid.util.lang import *
14
15 class 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):
26 indentation = self.newlineChar + (self.indentationChar * self.indentationLevel)
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):
38 ## print "--> characters(%s)" % content
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:
46 indentation += self.newlineChar + (self.indentationChar * self.indentationLevel)
47 ## indentation += self.indentationChar * self.indentationLevel
48 else:
49 self.hitCharData = False
50 ## self.xmlOutput += '%s</%s>%s' % (indentation, self.elementStack.pop(), self.newlineChar)
51 self.xmlOutput += '%s</%s>' % (indentation, self.elementStack.pop())
52
53 def getXMLString(self):
54 return self.xmlOutput[1:]
55
56 def xmlprettyprint(xmlstr, spaces=4):
57 xpp = XMLPrettyPrinter(indentationChar=' ' * spaces)
58 xml.sax.parseString(xmlstr, xpp)
59 return xpp.getXMLString()
60
61 if isMain(__name__):
62 simpleTestString = """<one>some text<two anattr="booga">two's data</two></one>"""
63 print xmlprettyprint(simpleTestString)
64