Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Remove level of elements (preserving their children) in XML::Twig?

by mirod (Canon)
on Mar 01, 2012 at 03:58 UTC ( #957088=note: print w/ replies, xml ) Need Help??


in reply to Remove level of elements (preserving their children) in XML::Twig?

There is a method in XML::Twig that does just what you want: erase.

Below is an example, with a couple of ways to solve the problem. I am sure there are others.

#!/usr/bin/perl use strict; use warnings; use autodie qw(open); use Test::More; use XML::Twig; my( $in, $expected)= do { local $/="\n\n"; <DATA>; }; is( remove_policy_rule( $in), $expected, 'simplest code'); is( with_flush( $in), $expected, 'with flush'); done_testing(); sub remove_policy_rule { my( $in)= @_; my $t= XML::Twig->new( twig_handlers => { policyrules => sub { $_- +>erase; } }, pretty_print => 'indented', ) ->parse( $in); return $t->sprint; } sub with_flush { my( $in)= @_; my $out; open( my $fh, '>', \$out); my $t= XML::Twig->new( twig_handlers => { policyrules => sub { $_- +>erase; $_[ +0]->flush( $fh); } }, pretty_print => 'indented', ) ->parse( $in); return $out; } __DATA__ <?xml version="1.0" encoding="UTF-8"?> <policy name="Cur_policy" version="3.2.1"> <policyrules> <Rule Action="allow" Enabled="true" RuleID="F68E32"> <source addr="10.4.5.3" srcport="any"/> <dest addr="199.5.4.3" destport="80"/> </Rule> <Rule Action="allow" Enabled="true" RuleID="78E21D"> <source addr="10.4.0.0-10.4.255.255" srcport="any"/> <dest addr="any" destport="80"/> </Rule> </policyrules> </policy> <?xml version="1.0" encoding="UTF-8"?> <policy name="Cur_policy" version="3.2.1"> <Rule Action="allow" Enabled="true" RuleID="F68E32"> <source addr="10.4.5.3" srcport="any"/> <dest addr="199.5.4.3" destport="80"/> </Rule> <Rule Action="allow" Enabled="true" RuleID="78E21D"> <source addr="10.4.0.0-10.4.255.255" srcport="any"/> <dest addr="any" destport="80"/> </Rule> </policy>


Comment on Re: Remove level of elements (preserving their children) in XML::Twig?
Download Code
Re^2: Remove level of elements (preserving their children) in XML::Twig?
by jdbaldwin23 (Initiate) on Mar 01, 2012 at 19:06 UTC

    Gobsmacked at the awesomeness of all the replies. But the one with the erase method (used in a way I hadn't tried) is it and my preliminary result on the (very big and complex) real-world data is encouraging. Thank you all.

    jd

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://957088]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2015-07-05 18:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (67 votes), past polls