Line 22 needs to be corrected - you have a syntax error in omitting a comma from your list assignment, and you likely meant to copy the contents of the argument array (@_) and not the default input variable ($_). That should read my ($path, $hash) = @_;. Of course, you call that function with no arguments, so that is likely not going to work very well for you.
Your posted XML is not well-formed. You have an opening Servicelist tag but no closing one.
You are interacting with your references incorrectly on lines 35 & 36. Read perlreftut for an intro to interacting with references.
Single quotes do not interpolate whereas double quotes do, so on line 36 you likely mean "$elem2"; this is for your purposes a no-op since it should already be a string, so it would be better written as $elem2.
Your Service element does not contain the attribute Id, and your Customermodules and Suppliermodules elements do not have Service attributes. It might do some good to review the difference between an element and an attribute -- see XML#Key_terminology.
This is an example script that takes the XML you have provided (modified to be well-formed) and extracts a list of type and nr attributes from the Hardwaremodule elements in Suppliermodules from the Service tags. It should hopefully give you an idea how to proceed, particularly when read with the documentation of XML::LibXML::Reader.
#!/usr/bin/perl use warnings; use strict; use XML::LibXML; 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'); $reader->nextElement( 'Suppliermodules' ); while ( $reader->nextElement( 'Hardwaremodule' )) { my $module = {}; $module->{type} = $reader->getAttribute('Type'); $module->{nr} = $reader->getAttribute('Nr'); push @{$hash_ref->{$number}}, $module; } } 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>
In reply to Re: how to get attribute values and store in a hash.
by kennethk
in thread how to get attribute values and store in a hash.
by veerubiji
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |