Forum: Ruby Finding best way to pretty print XML files

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
0de674f389b37299939bb4d0b308f371?d=identicon&s=25 Pk Z. (pk_z)
on 2011-01-11 08:35
Havn't found best soultion to pretty print XML:

REXML: It has pp functionality, but it wrap elements like <a>content</a>

Nokogiri: there is a approch to pp, see ex:

# Pretty print XML
require "nokogiri"

def write(buffer)

  xsl =<<XSL
<xsl:stylesheet version="1.0"
  <xsl:output method="xml" encoding="UTF-8" indent="yes"/>

<xsl:strip-space elements="*"/>
<xsl:template match="/">
  <xsl:copy-of select="."/>


    doc = Nokogiri::XML(buffer)
    xslt = Nokogiri::XSLT(xsl)
    out =  xslt.transform(doc)

But nokogiri has another problem, which unwrap CDATA.

Any better solution? Thanks. And apologize for my poor english.
0de674f389b37299939bb4d0b308f371?d=identicon&s=25 Pk Z. (pk_z)
on 2011-01-12 01:53
0 resp.  ToT
13120f1de7c199861733f2cfd349d860?d=identicon&s=25 Zimbatm ... (zimbatm)
on 2011-01-13 00:19
(Received via mailing list)
Sorry if you haven't got any help,

could you provide more informations to the output you want ?

There are many ways to indent XML code. Maybe you don't want to wrap
with <a>content</a>, but what if the content is longer ? Do you have a
column limit ?

In your place, I would take the pp code of nokogiri and tweak it until
gives me what I want.

Hope that help,

2011/1/12 Pk Z. <>:
Mike Dalessio (Guest)
on 2011-01-13 01:05
(Received via mailing list)
In my experience, everyone has a different definition of "pretty
If you want to get more specific about what you'd like to see, perhaps
people can give you a more specific answer.
5a42607d0beef24afc852bd44f1ae9d1?d=identicon&s=25 James Noyes (greatwhitedork)
on 2011-09-01 20:55
""But nokogiri has another problem, which unwrap CDATA.""

You can't preserve CDATA or !ENTITY using XSLT.
The XML parser will expand them, and there is absolutly no way to
prevent it.  (It causes many headaches for me.)

You would have to do it strictly with regular expressions, treating the
XML as text.
This topic is locked and can not be replied to.