sunnybrad
asked on
From XML to Comma separated format
Hi all:
I have perl, version 4.0 on Solaris. How do you go about parsing an XML document and creating a file in a comma separated format.
I want to know the big picture here. Also small examples with code will be very helpful.
Best Regards
-sunnybrad
I have perl, version 4.0 on Solaris. How do you go about parsing an XML document and creating a file in a comma separated format.
I want to know the big picture here. Also small examples with code will be very helpful.
Best Regards
-sunnybrad
normally i prefer xslt for such a task.
but if you insist using perl...please show a sample of your xml.
but if you insist using perl...please show a sample of your xml.
If the XML has got only a few types of tags(for eg., the whole XML file has got some 10 tags that are repeated thru out the document) then, it is better to use the regular expression.
It's hard to give a detailed answer without knowing the structure of your XML file, but you might be able to get some ideas from this:
#!/usr/bin/perl
use strict;
use warnings;
use XML::XPath;
my $xp = XML::XPath->new(ioref => \*DATA);
my $head;
foreach my $r ($xp->findnodes('//record' )) {
my @fields;
my @head;
foreach my $f ($r->findnodes('./*')) {
push @fields, $f->findvalue('.');
push @head, $f->getName unless $head;
}
unless ($head) {
print join ',', map { qq("$_") } @head;
print "\n";
$head++;
}
print join ',', map { qq("$_") } @fields;
print "\n";
}
__END__
<data>
<record>
<field1>foo</field1>
<field2>bar</field2>
<field3>baz</field3>
</record>
<record>
<field1>foo</field1>
<field2>bar</field2>
<field3>baz</field3>
</record>
</data>
#!/usr/bin/perl
use strict;
use warnings;
use XML::XPath;
my $xp = XML::XPath->new(ioref => \*DATA);
my $head;
foreach my $r ($xp->findnodes('//record'
my @fields;
my @head;
foreach my $f ($r->findnodes('./*')) {
push @fields, $f->findvalue('.');
push @head, $f->getName unless $head;
}
unless ($head) {
print join ',', map { qq("$_") } @head;
print "\n";
$head++;
}
print join ',', map { qq("$_") } @fields;
print "\n";
}
__END__
<data>
<record>
<field1>foo</field1>
<field2>bar</field2>
<field3>baz</field3>
</record>
<record>
<field1>foo</field1>
<field2>bar</field2>
<field3>baz</field3>
</record>
</data>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
yeah, you better write a shell script instead if using perl4
Use XML::Simple
my $hash_ref= XMLin("$XmlConfigFile");
my %Config = undef;
%Config = %$hash_ref;
# Now I have a hash %Config that represents the structure of the XML file with keys and values.
# We can go though the keys and save it to one or multiple text files, separating values by commas or any other character.
# We have full control over the structure of the resulting text file.