Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

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

by mirod (Canon)
on Mar 01, 2012 at 03:58 UTC ( [id://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>

Replies are listed 'Best First'.
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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://957088]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (4)
As of 2024-03-29 12:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found