[thelist] [XML]

Marcus Andersson marcus at bristav.se
Wed May 19 08:50:22 CDT 2004

You can use this stylesheet to prettyprint XML2HTML. I just wrote it so it's not feature complete (as in it 
doesn't copy comments or processing instructions and it doesn't preserve white space (but you don't want that 
anyway since you want a prettyprinter, right?))

All it does is print the content and keeps track of the level to output spaces on each new line.


<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <!-- Add or remove &#160; in the following variable. Each one is a space in the indent. So right now there 
is two spaces indent for each level -->
   <xsl:variable name="indent">&#160;&#160;</xsl:variable>

   <xsl:template match="/">
           <xsl:apply-templates select="*|node()">
             <xsl:with-param name="depth" select="0"/>

   <xsl:template match="*">
     <xsl:param name="depth"/>

     <xsl:call-template name="doIndent">
       <xsl:with-param name="length" select="$depth"/>

     &lt;<xsl:value-of select="name()"/>
     <xsl:text> </xsl:text>

     <xsl:for-each select="@*">
       <xsl:value-of select="name()"/>="<xsl:value-of select="."/>"
       <xsl:when test="node()">&gt;<br/>
         <xsl:apply-templates select="node()">
           <xsl:with-param name="depth" select="number($depth) + 1"/>
         <xsl:call-template name="doIndent">
           <xsl:with-param name="length" select="$depth"/>
         &lt;/<xsl:value-of select="name()"/>&gt;<br/>

   <xsl:template match="text()">
     <xsl:param name="depth" select="0"/>
     <!-- Should've been enough with string(.) to test for white-space only but there seems to be a bug in 
Mozilla XSLT on this -->
     <xsl:if test="string-length(normalize-space(string(.))) &gt; 0">
       <xsl:call-template name="doIndent">
         <xsl:with-param name="length" select="$depth"/>
       <xsl:value-of select="."/><br/>

   <xsl:template name="doIndent">
     <xsl:param name="length"/>
     <xsl:if test="number($length) &gt; 0">
       <xsl:copy-of select="$indent"/>
       <xsl:call-template name="doIndent">
         <xsl:with-param name="length" select="number($length) - 1"/>


Adriano Castro wrote:

>     I have an XML file that has been created by a program. Problem is the whole
> file is one huge line of text instead of indented chunks of code.
>     How can I format this automatically to be a bit more human readable?
>     I've tried opening it on the browser, copy the structured code and then
> paste it on my text editor. Unfortunately the hyphens (minus characters) from
> the treeview also come along with the code and are causing some problems.
>     What do you suggest?
>     Azif
> --
> www.adrianocastro.net · there's more hidden inside
> [azifwekare : the alter ego]

More information about the thelist mailing list