]>
git.saurik.com Git - wxWidgets.git/blob - wxPython/samples/ide/activegrid/util/xmlprettyprinter.py
1 #----------------------------------------------------------------------------
2 # Name: xmlprettyprinter.py
5 # Author: John Spurling
9 # Copyright: (c) 2004-2005 ActiveGrid, Inc.
10 # License: wxWindows License
11 #----------------------------------------------------------------------------
13 from activegrid
.util
.lang
import *
15 class XMLPrettyPrinter(xml
.sax
.ContentHandler
):
16 def __init__(self
, indentationChar
=' ', newlineChar
='\n'):
18 self
.indentationLevel
= 0
19 self
.indentationChar
= indentationChar
20 self
.elementStack
= []
21 self
.newlineChar
= newlineChar
22 self
.hitCharData
= False
24 ## ContentHandler methods
25 def startElement(self
, name
, attrs
):
26 indentation
= self
.newlineChar
+ (self
.indentationChar
* self
.indentationLevel
)
27 # build attribute string
29 for attr
in attrs
.getNames():
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
37 def characters(self
, content
):
38 ## print "--> characters(%s)" % content
39 self
.xmlOutput
+= content
40 self
.hitCharData
= True
42 def endElement(self
, name
):
43 self
.indentationLevel
-= 1
45 if not self
.hitCharData
:
46 indentation
+= self
.newlineChar
+ (self
.indentationChar
* self
.indentationLevel
)
47 ## indentation += self.indentationChar * self.indentationLevel
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())
53 def getXMLString(self
):
54 return self
.xmlOutput
[1:]
56 def xmlprettyprint(xmlstr
, spaces
=4):
57 xpp
= XMLPrettyPrinter(indentationChar
=' ' * spaces
)
58 xml
.sax
.parseString(xmlstr
, xpp
)
59 return xpp
.getXMLString()
62 simpleTestString
= """<one>some text<two anattr="booga">two's data</two></one>"""
63 print xmlprettyprint(simpleTestString
)