I wanted to build an awesome place for people to discuss module specific issues, but I don't have any more time for this, and there are much better places to discuss Perl-related issues. I'd recommend asking your question on Stack Overflow or on Perl Monks.
If you are looking for a Perl tutorial or Perl-related news, I hope these links will serve you well.
Posted on 2007-07-05 13:33:21-07 by stevieray in response to 5637
Re: Checking a twig root for existence of element?

Not sure if you want to test for existence ANYWHERE under the root or just the top level.
In any case I had a script that recursively walked the nodes to display hierarchy that I adapted to test for tags in a list stored in @required.

Imagine an XML doc with the following structure -

<book> <title>XML Wrapping</title> <author>Hubie Illin</author> <chapters> <chapter num="1"> <title>Run XML</title> <text> If at first you don't succeed, parse, parse again. </text> </chapter> </chapters> <price>19.95</price> </book>

You could test for given tags using something like the script below. I even added a test for the case of the title tag must not only exist, but exist under the chapter parent.

You can probably change the syntax of the required tag list to include notation for nested tags like chapter:title and handle parsing them in the loop that tests the tags.

Hope this helps
Steve
#!/usr/bin/perl #================================= # Program: check_tags.pl #================================= # use strict; use XML::Twig; sub print_error; my $filename = shift; print_error "Filename is required" unless ($filename); print "\n"; print "Parse file: $filename\n\n"; print_error "File not found : $filename" unless (-e $filename); my @required = qw(title author price); my %found_required = map { $_ => 0 } @required; # init all to not found my $twig = new XML::Twig; $twig->parsefile($filename); my $root = $twig->root; # get the root of the twig check_children($root); for my $tag (sort keys %found_required) { print "$tag: ", ($found_required{$tag}) ? "Found\n" : "NOT found\n"; } exit; #===================================== sub check_children { my $elem = shift; my $tag = $elem->tag; my $level = $elem->level; my $path = $elem->path; my $spacer = ' ' x $level; print "${spacer}Level $level tag = $tag [$path]\n"; my $found = grep { $_ eq $tag } @required; my @children = $elem->children; # get the child list if ($found) { if ($tag eq 'title') { my $in_chapter = $elem->in_context('chapter'); $found_required{$tag} = 1 if ($in_chapter); } else { $found_required{$tag} = 1; } } if (@children) { for my $child (@children) { check_children($child); } } } #------------------------------------- sub print_error { my $msg = shift; print STDERR "\nERROR>> $msg\n\n"; exit -1; }
Direct Responses: Write a response