in reply to XML parsing problem

If you want to query your XML-file, XPath is the way: And here is an example (I slightly changed your XML-file so all elements have different content):
use strict; use XML::XPath; use XML::XPath::XMLParser; my $xp = XML::XPath->new( xml => *DATA ); print 'There are ', $xp->find('queries/query')->size, " 'query' nodes. +\n"; foreach my $element (qw/topN layer filter name datatype/) { print "$element: ", ( join ', ', map { XML::XPath::XMLParser::as_string($_) =~ />([^<]*)</ } $xp->find("queries/query/$element")->get_nodelist ), "\n"; } ## end foreach my $element (qw/topN layer filter name datatype/) __DATA__ <?xml version='1.0'?> <queries> <query> <name>topHosts 20</name> <layer>LINK 20</layer> <topN>20</topN> <datatype>topHosts 20</datatype> <filter></filter> </query> <query> <name>topHosts 120</name> <layer>LINK 120</layer> <topN>120</topN> <datatype>topHosts 120</datatype> <filter></filter> </query> </queries>
Output:
There are 2 'query' nodes. topN: 20, 120 layer: LINK 20, LINK 120 filter: name: topHosts 20, topHosts 120 datatype: topHosts 20, topHosts 120
And yes I know that the regex to extract the text-data from the nodes is very crude ...

Update: added a code example.

Update2: simplified and shortened code

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Replies are listed 'Best First'.
Re^2: XML parsing problem
by grantm (Parson) on Mar 12, 2009 at 23:52 UTC
    If you want to query your XML-file, XPath is the way

    I agree with that 100% however XML::LibXML is a much better module to recommend than XML::XPath. The libxml implementation is much faster, uses less memory and is currently being maintained.