If you want to print all the info from the XML, than a better approach is to use the 'simplify' method of XML::Twig (or XML::Simple) to create a Perl data structure.
use strict;
use warnings;
use XML::Twig;
use Data::Dumper;
my $twig = new XML::Twig();
my $config = $twig->parsefile('invoice2.xml')->simplify();
print Dumper( $config);
With XML::XPath I see only a more tedious way (it's true that I don't have much experience with it.)
Also I changed the xml a little:
<Invoices>
<Invoice>
<InvoiceHeader>
<InvoiceType>IT1</InvoiceType>
<Supplier>
<Name>Sup1</Name>
<OrgNumber>Org1</OrgNumber>
</Supplier>
</InvoiceHeader>
<InvoiceDetails>
<BaseItemDetails>
<Description>description11</Description>
<PerQuantity></PerQuantity>
</BaseItemDetails>
<BaseItemDetails>
<Description>description12</Description>
<PerQuantity>101</PerQuantity>
</BaseItemDetails>
</InvoiceDetails>
</Invoice>
<Invoice>
<InvoiceHeader>
<InvoiceType>IT2</InvoiceType>
<Supplier>
<Name>Sup1</Name>
<OrgNumber>Org2</OrgNumber>
</Supplier>
</InvoiceHeader>
<InvoiceDetails>
<BaseItemDetails>
<Description>description21</Description>
<PerQuantity></PerQuantity>
</BaseItemDetails>
<BaseItemDetails>
<Description>description21</Description>
<PerQuantity>101</PerQuantity>
</BaseItemDetails>
</InvoiceDetails>
</Invoice>
</Invoices>
use strict;
use warnings;
use XML::XPath;
use XML::XPath::XMLParser;
my $xp = XML::XPath->new(filename => 'invoice2.xml');
my $nodeset = $xp->find('//Invoices/Invoice');
foreach my $node ($nodeset->get_nodelist) {
my $it = $node->find('InvoiceHeader/InvoiceType')->string_value;
print "IT: $it\n";
my $spn = $node->find('Supplier/Name')->string_value;
print " SPN: $it\n";
my $des = $node->find('InvoiceDetails/BaseItemDetails/Description'
+)->string_value;
print " DES: $des\n";
# ...
# You got the idea, yes?
}
Good coding, Stefan
Update:
'TwigRoots' option is not needed in the XML::Twig example. You may want to use 'forcearray',
'keyattr' or other options to get a consistent data structure.
Update2:
Removed 'TwigRoots' option from the code.
|