xmlformattingperl

How can I set the level of indention for pretty-printing XML in Perl?


I need to format my output to XML. Let´s say I get number in parameters and I want that this numbers means how much spaces would be there from previous parent element. For example number 2:

<?xml version="1.0"?>
<LEVEL1>
  <LEVEL2>
    <LEVEL3/>
  </LEVEL2>
</LEVEL1>

or for 4:

<?xml version="1.0"?>
<LEVEL1>
    <LEVEL2>
        <LEVEL3/>
    </LEVEL2>
</LEVEL1>

I like module XML::LibXML and is there way how can I do it in this module? Or which module can do this?

And one more thing, what if I want to have an option to set (or not) new line after heading? How can I do this?


Solution

  • With XML::Twig you can use set_indent to define the indent string:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use XML::Twig;
    
    my $indent_nb= shift @ARGV || 1;
    
    my $t= XML::Twig->new( pretty_print => 'indented');
    $t->set_indent( ' ' x $indent_nb);
    $t->parse( \*DATA)->print;
    
    __DATA__
    <?xml version="1.0"?>
    <LEVEL1>
      <LEVEL2>
        <LEVEL3/>
      </LEVEL2>
    </LEVEL1>