Libor Zapletal
Libor Zapletal

Reputation: 14102

Perl formatted output xml

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 modul XML::LibXML and is there way how can I do it in this modul? Or which modul 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? Thank you

Upvotes: 0

Views: 3398

Answers (3)

Aydin K.
Aydin K.

Reputation: 3367

I've just found 2 possible solutions for indenting in general:

1) Via XML::Twig: http://search.cpan.org/dist/XML-Twig/Twig.pm

2) Via XML::LibXML: You can set the indent-length via the toString-method.

Check the description for the format-parameter here: http://metacpan.org/pod/XML::LibXML::Document

Edit: Sorry, I was too fast. Your intention is to calculate the indent-size on base of the input-xml - right?

Upvotes: 2

Jan Kapellen
Jan Kapellen

Reputation: 1

You can use XML::LibXML "to_string" or "to_file" function. Both support "Format" as mentioned in http://metacpan.org/pod/XML::LibXML::Document. In the to_file function it is the second parameter after the filename.

The optional $format parameter sets the indenting of the output. This parameter is expected to be an integer value, that specifies that indentation should be used. The format parameter can have three different values if it is used:

If $format is 0, than the document is dumped as it was originally parsed

If $format is 1, libxml2 will add ignorable white spaces, so the nodes content is easier to read. Existing text nodes will not be altered

If $format is 2 (or higher), libxml2 will act as $format == 1 but it add a leading and a trailing line break to each text node.

libxml2 uses a hard-coded indentation of 2 space characters per indentation level. This value can not be altered on run-time.

you can view a small example on how to generate proper xml in perl on my blog.

Upvotes: 0

mirod
mirod

Reputation: 16161

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>

Upvotes: 3

Related Questions