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:

<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>
The relevant snippet of my Perl code looks like this:
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!


In reply to XML::Parser - Obtaining Attributes by DanielSpaniel

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.