]>
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 #----------------------------------------------------------------------------
12 from activegrid
.util
.lang
import *
17 class XMLPrettyPrinter(xml
.sax
.ContentHandler
):
18 def __init__(self
, indentationChar
=' ', newlineChar
='\n'):
20 self
.indentationLevel
= 0
21 self
.indentationChar
= indentationChar
22 self
.elementStack
= []
23 self
.newlineChar
= newlineChar
24 self
.hitCharData
= False
26 ## ContentHandler methods
27 def startElement(self
, name
, attrs
):
28 indentation
= self
.newlineChar
+ (self
.indentationChar
* self
.indentationLevel
)
29 # build attribute string
31 for attr
in attrs
.getNames():
33 attrstring
+= ' %s="%s"' % (attr
, value
)
34 self
.xmlOutput
+= '%s<%s%s>' % (indentation
, name
, attrstring
)
35 self
.indentationLevel
+= 1
36 self
.elementStack
.append(name
)
37 self
.hitCharData
= False
39 def characters(self
, content
):
40 ## print "--> characters(%s)" % content
41 self
.xmlOutput
+= content
42 self
.hitCharData
= True
44 def endElement(self
, name
):
45 self
.indentationLevel
-= 1
47 if not self
.hitCharData
:
48 indentation
+= self
.newlineChar
+ (self
.indentationChar
* self
.indentationLevel
)
49 ## indentation += self.indentationChar * self.indentationLevel
51 self
.hitCharData
= False
52 ## self.xmlOutput += '%s</%s>%s' % (indentation, self.elementStack.pop(), self.newlineChar)
53 self
.xmlOutput
+= '%s</%s>' % (indentation
, self
.elementStack
.pop())
55 def getXMLString(self
):
56 return self
.xmlOutput
[1:]
58 def xmlprettyprint(xmlstr
, spaces
=4):
59 xpp
= XMLPrettyPrinter(indentationChar
=' ' * spaces
)
60 xml
.sax
.parseString(xmlstr
, xpp
)
61 return xpp
.getXMLString()
64 simpleTestString
= """<one>some text<two anattr="booga">two's data</two></one>"""
65 print xmlprettyprint(simpleTestString
)