# -*- coding: utf-8 -*- import xml.dom from xml.dom import Node from xml.dom.minidom import parse import sys def strip_space(node): child=node.firstChild while child!=None: c=child.nextSibling if (child.nodeType==Node.TEXT_NODE and len(child.nodeValue.strip())==0): node.removeChild(child) else: strip_space(child) child=c return node # use sys.stdout.write instead of print to control the output # i.e. without added spaces between elements to print def compact(node,indent): if node==None: return if node.nodeType==Node.ELEMENT_NODE: sys.stdout.write(node.nodeName+'[') indent += (len(node.nodeName)+1)*" " attrs = node.attributes first=True for i in range(len(attrs)): if not first: sys.stdout.write('\n'+indent) sys.stdout.write('@'+attrs.item(i).nodeName + '['+attrs.item(i).nodeValue+']') first=False child=node.firstChild while child!=None: if not first: sys.stdout.write('\n'+indent) compact(child,indent) first=False child=child.nextSibling sys.stdout.write(']') elif node.nodeType==Node.TEXT_NODE: sys.stdout.write(node.nodeValue.strip()) doc = parse(sys.stdin) compact(strip_space(doc.documentElement),"") sys.stdout.write('\n')