| 1 |
# inspired by https://gist.github.com/sente/1083506 |
| 2 |
# The MIT License (MIT) |
| 3 |
|
| 4 |
# Copyright (c) 2016 Stuart Powers |
| 5 |
|
| 6 |
# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 |
# of this software and associated documentation files (the "Software"), to deal |
| 8 |
# in the Software without restriction, including without limitation the rights |
| 9 |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 |
# copies of the Software, and to permit persons to whom the Software is |
| 11 |
# furnished to do so, subject to the following conditions: |
| 12 |
|
| 13 |
# The above copyright notice and this permission notice shall be included in all |
| 14 |
# copies or substantial portions of the Software. |
| 15 |
|
| 16 |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 22 |
# SOFTWARE. |
| 23 |
|
| 24 |
import re |
| 25 |
|
| 26 |
|
| 27 |
def pretty_print(xmlstr, indent=' ', line_break='\n'): |
| 28 |
# python2 doesn't have nonlocal |
| 29 |
current = [0] |
| 30 |
|
| 31 |
def indent_line(line): |
| 32 |
addition = 0 |
| 33 |
|
| 34 |
if re.match(r'.+</\w[^>]*>$', line): |
| 35 |
# single line text element, don't change indentation |
| 36 |
addition = 0 |
| 37 |
elif re.match(r'^</\w', line) and current[0] > 0: |
| 38 |
# end of element and have padding, decrement indentation by one |
| 39 |
current[0] -= 1 |
| 40 |
elif re.match(r'^<\w[^>]*[^/]>.*$', line): |
| 41 |
# start of element, increment indentation by one |
| 42 |
addition = 1 |
| 43 |
else: |
| 44 |
# single line element, don't change indentation |
| 45 |
addition = 0 |
| 46 |
|
| 47 |
# update and store current indentation in outer function |
| 48 |
current[0] += addition |
| 49 |
|
| 50 |
# pad the line and return |
| 51 |
return (indent * (current[0] - addition)) + line |
| 52 |
|
| 53 |
# split the document into lines, indent each line, then rejoin lines |
| 54 |
return line_break.join( |
| 55 |
map( |
| 56 |
indent_line, |
| 57 |
re.sub('(>)(<)(/*)', r'\1\n\2\3', xmlstr).split('\n') |
| 58 |
) |
| 59 |
) |