• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1059
  • Last Modified:

writing the xml DOM data into xml file with proper indentation in perl

I am loading the content from an xml file using DOM. I am inserting some elements into the DOM. And now I am  writing the xml using perl XML::DOM::Node class's printToFile method. But i am not getting a properly structured  xml output. Can anyone suggest me about the options available in DOM parser perl module to write a structured xml?
2 Solutions
I usually use XML::Twig to output the nice formatted XML.

Please see attached code for example
my $parser = new XML::DOM::Parser;
my $dom = $parser->parse($xml);
my $book = $dom->createElement("Book");
my $twig = new XML::Twig;
   $twig->set_indent(" "x4);
print $twig->sprint;

Open in new window

late to the party here, but you could use XML::LibXML too
use XML::LibXML;
# input is a file
my $input = 'some_file.xml';
# create the parser
my $parser = XML::LibXML->new();
# parse a file
my $doc = $parser->parse_file($xml);
# use parse_string() for a string of XML
my $filename = 'out.xml';
my $format = 1;
# print out the string of formatted XML
print $doc->toString(1);
# write to file a string of formatted XML
$doc->toFile($filename, $format);

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now