Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: How to remove empty XML elements using XML::LibXML

by choroba (Cardinal)
on Feb 17, 2013 at 20:40 UTC ( [id://1019208]=note: print w/replies, xml ) Need Help??


in reply to How to remove empty XML elements using XML::LibXML

If you want to use a namespace prefix, you have to register it first:
#!/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;
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: How to remove empty XML elements using XML::LibXML
by FreakyGreenLeaky (Sexton) on Feb 18, 2013 at 04:23 UTC

    Thanks - that works perfectly when operating on 1.xml or another XML document object.

    Your sample uncovered another layer/problem:

    my XML document comes from Net::EPP::Frame (cpan.org says "This module implements a subclass of the XML::LibXML::Document..."), so I'm doing something wrong when I try:

    use Net::EPP::Frame; my $frame = Net::EPP::Frame::Command::Update::Contact->new; #... my $xpc = XML::LibXML::XPathContext->new($frame); $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())]', $frame->documentElement)) +{ $node = $node->parentNode->removeChild($node); } } print $frame->toString(1);

    My thinking is that because Net::EPP::Frame inherits from XML::LibXML::Document, I should be able to operate on $frame (the XML document) similarly to your original solution... but I'm missing something.

      I have no experience with Net::EPP::Frame. What error do you get, or how is the output different from your expectations? Also, what does ref $frame say?
      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

        Running my sample code produces no change at all, and no error. The offending XML elements are still there.

        ref $frame says

        Net::EPP::Frame::Command::Update::Contact

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-04-25 20:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found