Ignore:
Timestamp:
02/12/13 22:25:58 (14 months ago)
Author:
Ales Erjavec <ales.erjavec@…>
Branch:
default
Message:

Reworked ows pretty printing.

Minidom pretty printing does not preserve text section whitespace.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • Orange/OrangeCanvas/scheme/readwrite.py

    r11305 r11307  
    33""" 
    44import sys 
    5 import StringIO 
    65import shutil 
    76 
    87from xml.etree.ElementTree import TreeBuilder, Element, ElementTree, parse 
    9 from xml.dom import minidom 
    108 
    119from collections import defaultdict 
     
    435433    """ 
    436434    tree = scheme_to_etree(scheme) 
    437     buffer = StringIO.StringIO() 
     435 
     436    if pretty: 
     437        indent(tree.getroot(), 0) 
    438438 
    439439    if sys.version_info < (2, 7): 
    440440        # in Python 2.6 the write does not have xml_declaration parameter. 
    441         tree.write(buffer, encoding="utf-8") 
     441        tree.write(stream, encoding="utf-8") 
    442442    else: 
    443         tree.write(buffer, encoding="utf-8", xml_declaration=True) 
    444  
    445     if pretty: 
    446         dom = minidom.parse(StringIO.StringIO(buffer.getvalue())) 
    447         pretty_xml = dom.toprettyxml(encoding="utf-8") 
    448         buffer = StringIO.StringIO(pretty_xml) 
    449     else: 
    450         buffer.seek(0) 
    451  
    452     shutil.copyfileobj(buffer, stream) 
     443        tree.write(stream, encoding="utf-8", xml_declaration=True) 
     444 
     445 
     446def indent(element, level=0, indent="\t"): 
     447    """ 
     448    Indent an instance of a :class:`Element`. Based on 
     449    `http://effbot.org/zone/element-lib.htm#prettyprint`_). 
     450 
     451    """ 
     452    def empty(text): 
     453        return not text or not text.strip() 
     454 
     455    def indent_(element, level, last): 
     456        child_count = len(element) 
     457 
     458        if child_count: 
     459            if empty(element.text): 
     460                element.text = "\n" + indent * (level + 1) 
     461 
     462            if empty(element.tail): 
     463                element.tail = "\n" + indent * (level + (-1 if last else 0)) 
     464 
     465            for i, child in enumerate(element): 
     466                indent_(child, level + 1, i == child_count - 1) 
     467 
     468        else: 
     469            if empty(element.tail): 
     470                element.tail = "\n" + indent * (level + (-1 if last else 0)) 
     471 
     472    return indent_(element, level, True) 
Note: See TracChangeset for help on using the changeset viewer.