Wartbarkeit, Stabilität und Effektivität

XML-Formater

2009-11 04
Mi, 2009-11-04 09:21 -- mig

#!/usr/bin/python
import fileinput
import os
import re
import shutil
import sys
import tempfile
 
# (c) 2009 mig@xilab.net  
 
def pr(s, level):
    print '\t'*level + s
 
def format(data):
    fields = re.split('(<.*?>)', data.replace('\r\n', '\n').replace('\r', '\n'))
    level = 0
    l = 0
 
    while l < len(fields):
        f = fields[l]
        l = l + 1
        if f.strip() == '':
            continue
        if f[0] == '<' and f[1] not in ['/', '?', '!']:
            if fields[l][:2] == '</':
                f = f + fields[l]
                l = l + 1
                pr(f, level)
            elif fields[l+1][:2] == '</':
                f = f + fields[l].strip() + fields[l+1]
                l = l + 2
                pr(f, level)
            elif f[-2:] != '/>':
                pr(f, level)
                level = level + 1
        else:
            if f[:2] == '</':
                level = level - 1
            pr(f, level)
 
data = sys.stdin.read()
format(data)
#:set shiftwidth=4|set expandtab|set tabstop=4