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