]>
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 import xml
.sax
.handler
16 class XMLPrettyPrinter(xml
.sax
.ContentHandler
):
17 def __init__(self
, indentationChar
=' ', newlineChar
='\n'):
19 self
.indentationLevel
= 0
20 self
.indentationChar
= indentationChar
21 self
.elementStack
= []
22 self
.newlineChar
= newlineChar
23 self
.hitCharData
= False
25 ## ContentHandler methods
26 def startElement(self
, name
, attrs
):
27 indentation
= self
.newlineChar
+ (self
.indentationLevel
* self
.indentationChar
)
28 # build attribute string
30 for attr
in attrs
.getNames():
32 attrstring
+= ' %s="%s"' % (attr
, value
)
33 self
.xmlOutput
+= '%s<%s%s>' % (indentation
, name
, attrstring
)
34 self
.indentationLevel
+= 1
35 self
.elementStack
.append(name
)
36 self
.hitCharData
= False
38 def characters(self
, 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.indentationLevel * self.indentationChar)
47 indentation
+= self
.indentationLevel
* self
.indentationChar
49 self
.hitCharData
= False
50 self
.xmlOutput
+= '%s</%s>%s' % (indentation
, self
.elementStack
.pop(), self
.newlineChar
)
52 def getXMLString(self
):
53 return self
.xmlOutput
[1:]
55 def xmlprettyprint(xmlstr
, spaces
=4):
56 xpp
= XMLPrettyPrinter(indentationChar
=' ' * spaces
)
57 xml
.sax
.parseString(xmlstr
, xpp
)
58 return xpp
.getXMLString()
60 if __name__
== '__main__':
61 simpleTestString
= """<one>some text<two anattr="booga">two's data</two></one>"""
62 print prettyprint(simpleTestString
)