Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

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

by derby (Abbot)
on Feb 29, 2012 at 22:57 UTC ( #957048=note: print w/ replies, xml ) Need Help??


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

Not sure about XML::Twig but here's how I would do it with XML::LibXML:

#!/usr/bin/env perl use warnings; use strict; use XML::LibXML; my $file = shift || die "usage $0 <xmlfile>\n"; my $parser = XML::LibXML->new(); my $dom = $parser->parse_file( $file ); my $doc = $dom->documentElement(); my @rules = $doc->findnodes( '/policy/policyrules/Rule' ); my $newdom = XML::LibXML::Document->new( '1.0', 'UTF-8' ); my $newroot = $dom->createElement( 'policy' ); $newroot->setAttribute( 'name', 'Cur_policy' ); $newroot->setAttribute( 'version', '3.2.1' ); $newdom->setDocumentElement( $newroot ); foreach my $rule ( @rules ) { $newroot->appendChild( $rule ); } print $newdom->toString(1);

-derby

update: Doh! ... no need for a new document:

#!/usr/bin/env perl use warnings; use strict; use XML::LibXML; my $file = shift || die "usage $0 <xmlfile>\n"; my $parser = XML::LibXML->new(); my $dom = $parser->parse_file( $file ); my $doc = $dom->documentElement(); my @rules = $doc->findnodes( '/policy/policyrules/Rule' ); my $parent = $rules[0]->parentNode->parentNode; $parent->removeChildNodes(); $parent->appendChild( $_ ) foreach @rules; print $dom->toString(1);


Comment on Re: Remove level of elements (preserving their children) in XML::Twig?
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (13)
As of 2014-11-26 15:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (171 votes), past polls