Re: [xsl] How to get comments to indent on their own line in XML output?

Subject: Re: [xsl] How to get comments to indent on their own line in XML output?
From: Liam Quin <liam@xxxxxx>
Date: Sun, 6 Jul 2008 21:16:01 -0400
On Sun, Jul 06, 2008 at 02:33:59PM +0200, alan.painter@xxxxxxx wrote:
> I guess that I'm really expecting the simple case to work, where
> indentation comes out as a function of nested children without having
> to add extraneous text nodes.

First, you won't be able to match a comment in the input.
They are generally discarded before the XSLT processor sees the
result.

Second, there are several ways to get indented output, although
for configuration files you could consider using gconf directly
(assuming you are on Linux under GNOME).

One is to have a parameter you pass down at each level with
the number of spaces to indent by.

Another is to use a post-processor.

Another is to use an XSLT library that supports output indenting;
libxml/xsltproc might, although it's XSSLT 1 and not 2; if not,
you could probably do it in C or Java, depending on the processor,
with a custom serialization code.

I'd probably write a separate XSLT transformation that did nothing
except the indenting.

This is all assuming you are ignoring whitespace in the input,
rather than matching it.

Here's an example that does not ignore the space in the input:

input "boy.xml":
[[
<boy>
    <name>Simon</name>
    <socks>blue</socks>
    <comment>fast learner.</comment>
</boy>
]]

stylesheet
[[
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"; version="2.0" >
  <xsl:template match="/boy">
    <child gender="male">
      <xsl:apply-templates />
    </child>
  </xsl:template>
  <xsl:template match="name">
      <name><xsl:apply-templates /></name>
  </xsl:template>
  <xsl:template match="socks">
      <socks><xsl:apply-templates /></socks>
  </xsl:template>
  <xsl:template match="comment">
      <comment><xsl:apply-templates /></comment>
  </xsl:template>
</xsl:stylesheet>
]]

output
[[
<?xml version="1.0"?>
<child gender="male">
    <name>Simon</name>
    <socks>blue</socks>
    <comment>fast learner.</comment>
</child>
]]

Liam


-- 
Liam Quin, W3C XML Activity Lead, http://www.w3.org/People/Quin/
http://www.holoweb.net/~liam/ * http://www.fromoldbooks.org/

Current Thread