in reply to Re^2: how to get attribute values and store in a hash.
in thread how to get attribute values and store in a hash.
You have now provided an expected output, so I can modify my previous code to replicate your specified output, except of course that your quoted path's do not correspond to the paths in your XML and the order is different because your spec does not respect the order of the source document.
#!/usr/bin/perl use warnings; use strict; use XML::LibXML::Reader; use Data::Dumper; my $hash_ref; my $reader = XML::LibXML::Reader->new( IO => *DATA ); while ( $reader->nextElement( 'Service' )) { my $number = $reader->getAttribute( 'Num'); $hash_ref->{$number} = []; $reader->read; while (1) { if ( $reader->localName eq 'Customermodules' or $reader->localName eq 'Suppliermodules') { $reader->read; while (1) { if ($reader->localName eq 'Softwaremodule') { my $module = {}; $module->{Service} = $reader->getAttribute('Servic +e'); $module->{path} = $reader->getAttribute('Path'); push @{$hash_ref->{$number}}, $module; } elsif ($reader->localName eq 'Hardwaremodule') { my $module = {}; $module->{Type} = $reader->getAttribute('Type'); $module->{Nr} = $reader->getAttribute('Nr'); $module->{Servicenum} = $reader->getAttribute('Ser +vicenum'); $module->{path} = $reader->getAttribute('Path'); push @{$hash_ref->{$number}}, $module; } $reader->nextSibling() > 0 or last; } } $reader->nextSibling() > 0 or last; } } $reader->finish; print Dumper $hash_ref; __DATA__ <?xml version="1.0" encoding="UTF-8"?> <Servicelist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi +:noNamespaceSchemaLocation="file:///files/service.xsd"> <Service Num="B7a" Name="temperature sensor"> <Des>It delivers actual temperature in the form ov Volts</Des> <Customermodules> <Softwaremodule Service="ADC" Path="/main/ADCservice.xml"/> </Customermodules> <Suppliermodules> <Softwaremodule Service="input" Path="/main/inputservice.xml"/> <Softwaremodule Service="signal" Path="/main/signalservice.xml"/> <Hardwaremodule Type="engine" Nr="18" Servicenum="1" Path="/main/e +ngineservice.xml"/> <Hardwaremodule Type="motor" Nr="7" Servicenum="1" Path="/main/mo +torservice.xml"/> <Hardwaremodule Type="supply" Nr="1" Servicenum="1" Path="/main/sup +plyservice.xml"/> </Suppliermodules> </Service> </Servicelist>
outputs
$VAR1 = { 'B7a' => [ { 'path' => '/main/ADCservice.xml', 'Service' => 'ADC' }, { 'path' => '/main/inputservice.xml', 'Service' => 'input' }, { 'path' => '/main/signalservice.xml', 'Service' => 'signal' }, { 'Type' => 'engine', 'Servicenum' => '1', 'path' => '/main/engineservice.xml', 'Nr' => '18' }, { 'Type' => 'motor', 'Servicenum' => '1', 'path' => '/main/motorservice.xml', 'Nr' => '7' }, { 'Type' => 'supply', 'Servicenum' => '1', 'path' => '/main/supplyservice.xml', 'Nr' => '1' } ] };
|
|---|