You need to set up the top level structure of your output document outside of the while loop.
Also, even if this is nothing which fails your code at the moment, you should also concider using a hash instead of evaling symbolic variable names.
use strict;
use warnings;
use XML::Writer;
#use XML::Reader;
use IO::File;
open(my $fh,"./input.txt") or die "Cannot open input file.";
my $output = new IO::File(">converted_to_xml.xml"); #file to write the
+ converted content
my $writer = new XML::Writer(OUTPUT => $output); #write into the opene
+d file
my @array=qw(name emp_no designation salary);
$writer->xmlDecl("UTF-8"); #XML declaration
$writer->startTag("data"); # The root tag
while(my $input=<$fh>){
chomp($input);
next if !$input;
my %vals;
@vals{@array} = split /:/, $input;
$writer->startTag("row"); # enclosing tag for every data row
for my $name (@array) {
$writer->startTag($name);
$writer->characters($vals{$name});
$writer->endTag();
}
$writer->endTag(); # = endTag("row")
}
$writer->endTag(); # = endTag("data")
$writer->end();
$output->close();
Update: Typically you want some structure in the XML document, to address whole data rows. Added the "row" tag level for that.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|