DanielSpaniel has asked for the wisdom of the Perl Monks concerning the following question:
Hi,
I have an XML file from a third party which I need to process, which contains product data. Most of the file I can process without any problem, but I am having a problem trying to extract attribute values from one tag.
The XML looks similar to this pseudo-extract:
The relevant snippet of my Perl code looks like this:<products> <product> <description>Product description.</description> <image>some url</image> <categories> <category catname="Books" id="xyz" name="Books"/> </categories> <prodname>Product name</prodname> </product> <product> ... </product> </products>
my $file ='products.xml'; my $parser = new XML::Parser(Style=>'Stream'); eval {$parser->parsefile($file);}; sub StartTag { my ($expat, $tag, %attrs) = @_; if(%attrs) { print "Attributes:\n"; while(my($key, $value)=each(%attrs)) { print "\t$key => $value\n"; } }; if ($expat->within_element('products')) { push (@tagstack,lc($tag)); if ($tag eq'category') { # do whatever with the attributes ... } } }1;
However, despite playing around with this for ages, I cannot seem to get to retrieve the category attributes.
The code which checks if %attrs is empty or not never produces anything, and I don't understand where I'm going wrong.
Every product definitely has attributes in the "<categories><category catname="xyz" id="xxx" name="qqq"/></categories>" tags.
Any assistance would be much appreciated!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: XML::Parser - Obtaining Attributes
by toolic (Bishop) on Jan 25, 2014 at 00:16 UTC | |
by DanielSpaniel (Scribe) on Jan 25, 2014 at 00:36 UTC | |
|
Re: XML::Parser - Obtaining Attributes
by runrig (Abbot) on Jan 25, 2014 at 00:20 UTC | |
by DanielSpaniel (Scribe) on Jan 25, 2014 at 00:41 UTC | |
by runrig (Abbot) on Jan 27, 2014 at 17:13 UTC | |
|
Re: XML::Parser - Obtaining Attributes ( ddumper \@_ )
by Anonymous Monk on Jan 25, 2014 at 00:55 UTC |