#!/usr/bin/perl use warnings; use strict; use XML::LibXML; my $xml = XML::LibXML->load_xml( location => '1.xml'); my $xpc = XML::LibXML::XPathContext->new($xml); $xpc->registerNs('contact', 'urn:ietf:params:xml:ns:contact-1.0'); for my $name (qw(rem add)) { for my $node ($xpc->findnodes("//contact:$name".'[not(*|text()|@*|processing-instruction()|comment())]', $xml->documentElement)) { $node = $node->parentNode->removeChild($node); } } print $xml->serialize;