Here's my own gymnasticsy answer. If there is no better way, it will do. I sure wish there were a better way...
The replace_without_ns
method just copies nodes without the namespace. Any children elements that need the namespace get the declaration on them, instead. The code below moves the entire document into the null namespace:
use strict;
use warnings;
use XML::LibXML;
my $xml = <<'__EOI__';
<myDoc xmlns="foo">
<par xmlns:bar="www.bar.com" foo="bar">
<bar:foo stuff="junk">
<baz bar:thing="stuff"/>
fooey
<boof/>
</bar:foo>
</par>
</myDoc>
__EOI__
my $parser = XML::LibXML->new();
my $doc = $parser->parse_string($xml);
# remove namespaces for the whole document
for my $el($doc->findnodes('//*')){
if($el->getNamespaces){
replace_without_ns($el);
}
}
# replaces the given element with an identical one without the namespace
# also does this with attributes
sub replace_without_ns {
my ($el) = @_;
# new element has same name, minus namespace
my $new = XML::LibXML::Element->new( $el->localname );
#copy attributes (minus namespace namespace)
for my $att($el->attributes){
if($att->nodeName !~ /xmlns(?::|$)/){
$new->setAttribute($att->localname, $att->value);
}
}
#move children
for my $child($el->childNodes){
$new->appendChild($child);
}
# if working with the root element, we have to set the new element
# to be the new root
my $doc = $el->ownerDocument;
if( $el->isSameNode($doc->documentElement) ){
$doc->setDocumentElement($new);
return;
}
#otherwise just paste the new element in place of the old element
$el->parentNode->insertAfter($new, $el);
$el->unbindNode;
return;
}
print $doc->toStringHTML;