Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have the following problem, i have a series of XML tags in an array from position 0-17 in my case. what i want to do just for viewing purposes to see a clean version of my xml is to add in 3 or 4 spaces or a tab to indent. so that if i have array:
0 - <new> 1 - <mp3> 2 - <song title> 3 - </song title> 4 - </mp3> 5 - </new>
with 6 items and thsoe are it's contents. i can print out:
<new> <mp3> <song title> </song title> </mp3> </new>
if anyone can help that would be great. thx B

Replies are listed 'Best First'.
Re: Displaying XML
by BrowserUk (Patriarch) on Nov 25, 2002 at 23:24 UTC

    Like this?

    #! perl -slw use strict; use constant INDENT_SIZE => 4; my @xml = ( '<new>', '<mp3>', '<song title>', '</song title>', '</mp3>', '</new>', ); my $indent = 0; for (@xml) { $indent -= INDENT_SIZE if m|^</|; print ' ' x $indent, $_; $indent += INDENT_SIZE if m|^<[^/]|; } __END__ C:\test>215754 <new> <mp3> <song title> </song title> </mp3> </new> C:\test>

    Okay you lot, get your wings on the left, halos on the right. It's one size fits all, and "No!", you can't have a different color.
    Pick up your cloud down the end and "Yes" if you get allocated a grey one they are a bit damp under foot, but someone has to get them.
    Get used to the wings fast cos its an 8 hour day...unless the Govenor calls for a cyclone or hurricane, in which case 16 hour shifts are mandatory.
    Just be grateful that you arrived just as the tornado season finished. Them buggers are real work.

Re: Displaying XML
by pg (Canon) on Nov 26, 2002 at 00:06 UTC
    The easiest way, is probably to use XML::Parser, and when you new it, say:
    my $parser = new XML::Parser(Style => "Debug");
    When you parse your XML file, or a chunk of XML msg, it will display it in a easy-to-view way, not exactly the way you want, but maybe you will find it is useful.
      The easiest way, is probably to use XML::Parser

      The easiest way is probably to use an XML tool, but probably not XML::Parser, which is too low-level and quirky to be really considered easy to use.

      In this case you could just output the xml without bothering about the formating and then use a pretty-printer, like xml_pp or Tidy.

      If you got LibXML installed (gnome) then you can use
      xmllint --format infile.xml
      ...and you get well-formedness checking for free ;-)

      --
      Cheers, Joe