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

Dear User's:

I need to do some XML processing for my project. It is difficult to explain the actual requirement, so I will give an example. I am using XML::Twig for parsing and editing.

I have the following hash available to me.
%color = {'apple' => 'red', 'mango' => 'green'}

I have an XML file like the one below:
<?xml version="1.0" encoding="UTF-8"?> <Fruits> <Fruit name='apple'/> <Fruit name='orange'/> <Fruit name='mango'/> <Fruit name='Pineapple'/> </Fruits>
Given the XML and Hash I should provide something like this.
<?xml version="1.0" encoding="UTF-8"?> <Fruits> <Fruit name='apple'/> <Fruit name='mango'/> </Fruits>
That means I should retain only the fruits whose name is same as the keys in hash %color.

Please help with an XML::twig solution, because I have used it for XML parsing already. If it is not possible with XML::Twig please suggest a new solution.

Replies are listed 'Best First'.
Re: Validate XML based on hash data structure
by mirod (Canon) on Aug 17, 2005 at 22:12 UTC

    Untested, but should be pretty close to working:

    XML::Twig->new( twig_handlers => { Fruit => sub { $_->cut unless( $col +or{$_->att( 'name')}); } } ) ->parsefile( "fruits.xml");

    If memory is a problem, flush the twig at the end of the handler and after the parse.

      Thank you! It works