kevind0718 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Kind Monks:

After some more hacking and reading, found my errors

This code will do the trick:

my @el = $posNode->getElementsByTagName("itemName", 0); print scalar @el; print " " . $el[0]->getNodeName() . " " . nodeTypeText($el[0]- +>getNodeType()) ." \n" ;

bottom line getElementsByTagName works just fine.

I have been tasked with parsing a XML document that contains inventory info. The root level is <inventory> and then within inventory there are the inventory items, Ie <item1>, <item2>, <item3> ....... Within each inventory item there are many elements that describe that particular item. Ie <itemName>jeans501</itemName>, <itemId>j501ab</itemId>, <countryOrgin>mexico</countryOrgin>, <style>, etc...

Using XML::DOM I have written code that will rip through the XML and dump the elements one-by-one.

Here is my issue.

Given the node <item1> how do I ask for the node named "itemName" and ask for the node named "countryOrgin"? I wan t to ask for the info I need rather than ripping through the full item and then grapping the data. The way a database recordset would work.

I think that would be prettier code.

Thanks for considering my issue.

kd

Replies are listed 'Best First'.
Re: XML::DOM get Element By Name
by lorn (Monk) on Oct 15, 2007 at 17:26 UTC
Re: XML::DOM get Element By Name
by pajout (Curate) on Oct 15, 2007 at 20:32 UTC
    I do such jobs by this way (I did not really understood, what do you expect on output, so consider it as example...):
    #!/usr/bin/perl use XML::Trivial; my $xml = XML::Trivial::parse('<inventory> <item1> <itemName>jeans501</itemName> <itemId>j501ab</itemId> <countryOrgin>mexico</countryOrgin> </item1> <item2> <itemName>jeans502</itemName> <itemId>j502ab</itemId> <countryOrgin>mexico</countryOrgin> </item2> </inventory>'); foreach ($xml->{inventory}->ea) { print $_->en. "\n"; foreach ($_->ea) { print $_->en. " ".$_->ts."\n" if $_->ts ne ''; } }
    It prints
    item1 itemName jeans501 itemId j501ab countryOrgin mexico item2 itemName jeans502 itemId j502ab countryOrgin mexico
Re: XML::DOM get Element By Name
by ForgotPasswordAgain (Vicar) on Oct 15, 2007 at 15:36 UTC
    I'm sure there are several ways, but one way would be $item1->getElementsByTagName('itemName'). You could also use getChildNodes, getFirstChild, etc...