Subject: count the number of nodes in an XML doc
Posted By: crmpicco Post Date: 11/20/2006 11:19:29 AM
Is there a way in Perl to count the number of employee nodes in an XML document?

<?xml version='1.0'?>
    <staff>
        <employee>
            ... other nodes in here ...
        </employee>
        <employee>
            ... other nodes in here ...
        </employee>
        <employee>
            ... other nodes in here ...  
        </employee>
        <employee>
            ... other nodes in here ...
        </employee>
        <employee>
            ... other nodes in here ...
        </employee>
    </staff>


www.crmpicco.co.uk
www.ie7.com
Reply By: bluemin Reply Date: 11/28/2006 7:46:14 AM
undef $/;
$Str=(open (IN,"<$ARGV[0]"))?<IN>:die "$!";
$Str=~s/(\n|\t)*//g;
@count=$Str=~/<employee>/g;
print scalar(@count);


Reply By: crmpicco Reply Date: 12/8/2006 7:29:25 AM
thanks for that bluemin, here's another solution that worked:

#! /usr/bin/perl

# Craig R Morton
# Count number of nodes in an XML document
# Last_Edit: 08-Dec-2006

use warnings;
use strict;
use XML::Simple; # you will need to have this installed on your machine

# read the xml document 'employees.xml' as the input
my $xml = XMLin('employees.xml');

# get the number of nodes called 'employee'
my $count = @{$xml->{employee}}; 

print "We have $count employees\n";



www.crmpicco.co.uk
www.ie7.com
Reply By: crmpicco Reply Date: 12/8/2006 7:30:29 AM
http://search.cpan.org/CPAN/authors/id/G/GR/GRANTM/XML-Simple-2.16.tar.gz

www.crmpicco.co.uk
www.ie7.com

Go to topic 41498

Return to index page 98
Return to index page 97
Return to index page 96
Return to index page 95
Return to index page 94
Return to index page 93
Return to index page 92
Return to index page 91
Return to index page 90
Return to index page 89