• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1076
  • 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?
0
YUGA255
Asked:
YUGA255
2 Solutions
 
lyhanCommented:
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");
   $dom->getDocumentElement->appendChild($book);
my $twig = new XML::Twig;
   $twig->set_indent(" "x4);
   $twig->parse($dom->toString);
   $twig->set_pretty_print("indented");
#output
print $twig->sprint;

Open in new window

0
 
kawasCommented:
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

0
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

Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

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