p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   Perl (http://p2p.wrox.com/forumdisplay.php?f=196)
-   -   count the number of nodes in an XML doc (http://p2p.wrox.com/showthread.php?t=50526)

crmpicco November 20th, 2006 12:19 PM

count the number of nodes in an XML doc
 
Is there a way in Perl to count the number of employee nodes in an XML document?
Code:

<?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

bluemin November 28th, 2006 08:46 AM

undef $/;
$Str=(open (IN,"<$ARGV[0]"))?<IN>:die "$!";
$Str=~s/(\n|\t)*//g;
@count=$Str=~/<employee>/g;
print scalar(@count);



crmpicco December 8th, 2006 08:29 AM

thanks for that bluemin, here's another solution that worked:
Code:

#! /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

crmpicco December 8th, 2006 08:30 AM

http://search.cpan.org/CPAN/authors/...le-2.16.tar.gz

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


All times are GMT -4. The time now is 10:46 AM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.