Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
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 imbibing at the Monastery: (5)
As of 2015-07-30 06:08 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 (270 votes), past polls