[lxml-dev] altering the indent of the pretty output

Dirk Rothe d.rothe at semantics.de
Wed Feb 4 18:59:35 CET 2009


On Wed, 04 Feb 2009 17:50:40 +0100, Ronny Pfannschmidt  
<Ronny.Pfannschmidt at gmx.de> wrote:

> Hi,
>
> i'm currently porting gazpacho (a wysiwyg gtk ui file editor) to lxml,
> unfortunately the pretty printer prints with an indent of 2 and in order
> to match the convention i need an indent of 4
>
> is there any simple way to archive pretty dumping to a file with an
> indent of 4?

You could adapt the following XSL Transformation:

prettyXSL = """<?xml version="1.0" encoding="UTF-8"?>
                 <xsl:stylesheet version="1.0"  
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
                     <xsl:output encoding="UTF-8" method="xml"/>
                     <xsl:param name="indent-increment" select="'   '"/>
                     <xsl:template match="* |  
comment()|processing-instruction()">
                         <xsl:param name="indent" select="'&#xA;'"/>
                         <xsl:value-of select="$indent"/>
                         <xsl:copy>
                             <xsl:copy-of select="@*"/>
                             <xsl:apply-templates>
                                 <xsl:with-param name="indent"  
select="concat($indent, $indent-increment)"/>
                             </xsl:apply-templates>
                             <xsl:if test="*">
                                 <xsl:value-of select="$indent"/>
                             </xsl:if>
                         </xsl:copy>
                     </xsl:template>
                     <!-- WARNING: this is dangerous. Handle with care -->
                     <xsl:template match="text()[normalize-space(.)='']"/>
                 </xsl:stylesheet>"""

def prettyPrint(tree):
     xslt_doc = etree.fromstring(prettyXSL)
     if isinstance(tree, basestring):
         doc = etree.fromstring(tree)
     else:
         doc = tree
     transform = etree.XSLT(xslt_doc)
     return etree.tostring(transform(doc))

--dirk


More information about the lxml-dev mailing list