Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Use perl to write XML from a flat file

Status
Not open for further replies.

aforstie

Programmer
Jun 19, 2006
19
US
I am wondering if perl can be used to write an xml file from a pipe-delimited file. I want to take something in a file that might look like:

ID|Name|City|State|Country

And try to write XML that might look like:

<item-list>
<item>
<location city="City" state="State" country="Country"/>
</item>
</item-list>

If there are two items in the same City/State/Country, I only want one <location> XML element for both. What I want in the end is an XML document that lists all the locations where I have one or more item.

Any ideas on how to do this? Perhaps a sample script somehwhere I can review? I have done a lot of BASH scripting, but very little perl. This seemed like a good chance for me to make the jump to perl.

Thanks in advance!
 
I have a script that works and is writing the XML file as expected. Now I would like to add an enhancement that would eliminate duplicate <location> elements in the XML file. For example if I have two items in Phoeninx, AZ in the flat file, I would write only one <locaction> element, I need to match on city and state.

Here is the script I use to parse through the flat file to write the XML file.

@fields = split(/\|/,<>);

$index = 0;
foreach $field (@fields) {
if ($field =~ /^(.*)\(/) {
$positions{$1} = $index;
}
$index++;
}

$skip = <>;
@lines = <>;

$handle = "locations";

foreach $_ (@lines) {
@data = split(/\|/);

if ($data[$positions{'CountryRegion'}]) {

if (!$files{$handle}) {
# open the file and start the xml
open($handle, ">$handle.xml") || die "Could not open $handle.xml: $!\n";
$files{$handle} = 1;
print $handle "<locations>\n";

if (is_match($data[$positions{'Chain'}]) eq "true") {
print $handle " <location city=\"$data[$positions{'PrimaryCity'}]\"";
$data[$positions{'CountryRegion'}] && print $handle " state=\"$data[$positions{'Subdivision'}]\"";
print $handle " country=\"$data[$positions{'CountryRegion'}]\"/>\n";
}
}

}
}

# now close all the files
foreach $file (keys %files) {
print $handle "</locations>\n";
close $file;
}

sub is_match {
if ($_[0] eq "M") {
return true;
} else {
return false;
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top