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

Here's how I'd do it with XML::LibXML:

use XML::LibXML 1.93; use XML::LibXML::PrettyPrint qw/print_xml/; my $doc = XML::LibXML->load_xml(IO => \*DATA); $doc -> findnodes('//policyrules') -> foreach(sub { my $elem = shift; $elem->parentNode->appendChild($_) foreach $elem->childNod +es; $elem->parentNode->removeChild($elem); }); print_xml($doc); __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>
  • Comment on Re: Remove level of elements (preserving their children) in XML::Twig?
  • Download Code

Replies are listed 'Best First'.
Re^2: Remove level of elements (preserving their children) in XML::Twig?
by tobyink (Canon) on Mar 01, 2012 at 03:05 UTC

    With PerlX::MethodCallWithBlock it can get even prettier...

    use XML::LibXML 1.93; use XML::LibXML::PrettyPrint qw/print_xml/; use PerlX::MethodCallWithBlock; my $doc = XML::LibXML->load_xml(IO => \*DATA); $doc -> findnodes('//policyrules') -> foreach { my $elem = shift; $elem->parentNode->appendChild($_) foreach $elem->childNodes; $elem->parentNode->removeChild($elem); }; print_xml($doc);

    It almost makes me want to weep.

     

    I can get it down to a single chain, but then it starts looking a little obfuscated...

    use XML::LibXML 1.93; use XML::LibXML::PrettyPrint qw/print_xml/; use PerlX::MethodCallWithBlock; XML::LibXML -> load_xml(IO => \*DATA) -> findnodes('//policyrules') -> foreach { my $elem = shift; $elem->parentNode->appendChild($_) foreach $elem->childNodes; $elem->parentNode->removeChild($elem); } -> map { $_->ownerDocument } -> foreach { print_xml $_ and exit };