Here is the Sample data that am trying to parse to extract attribute value corresponding to node Company : CID, Name, Symbol, Value for all the Company nodes under Companies node
<?xml version="1.0" encoding="UTF-8"?>
<StockRecords xmlns="http://url1"
xmlns:ref="http://url2"
xmlns:xsi="http://url3">
<Companies>
<Company>
<CID>123</CID>
<Name>Google</Name>
<Symbol>GOOG</Symbol>
<Value>1234</Value>
</Company>
</Companies>
</StockRecords>
Following are the 2 variants that I tried. Variant 1
use XML::LibXML;
my $filename = "test.xml";
my $dom = XML::LibXML->load_xml(location => $filename);
foreach my $sample ($dom->findnodes( '/Companies/Company' )) {
print Dumper($sample);
last;
}
Variant 2: Since there are namespaces involved in it, XPathContext to be specified.
use XML::LibXML;
my $filename = "test.xml";
my $parser = XML::LibXML->new();
my $xmldoc = $parser->parse_file($filename);
my $root = $xmldoc->getDocumentElement;
my @l = $root->getElementsByTagName('StockRecords');
my $xc = XML::LibXML::XPathContext->new($root);
$xc->registerNs("ns1", "http://url1");
$xc->registerNs("ref", "http://url2");
$xc->registerNs("xsi", "http://url3");
Am not able to extract data for any attribute for the node. I did take a look at other answers, LibXML documentation still there is something am missing. Please help me with some pointers. Thanks
use strict;
use warnings;
use feature qw( say );
use XML::LibXML qw( );
use XML::LibXML::XPathContext qw( );
my $doc = XML::LibXML->load_xml( location => $ARGV[0] );
my $xpc = XML::LibXML::XPathContext->new();
$xpc->registerNs( ns1 => "http://url1" );
for my $company_node ($xpc->findnodes("/ns1:StockRecords/ns1:Companies/ns1:Company", $doc)) {
say $xpc->findvalue("ns1:CID", $company_node);
say $xpc->findvalue("ns1:Name", $company_node);
}