psini has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I have a tree generated by XML::Parser(Style => 'tree'). My program modifies it and needs to serialize it back to a XML file.

sub serialize { my $writer=shift; my $tag=shift; my $value=shift; if ($tag eq 0) { $writer->characters($value); } else { $writer->startTag($tag,%{$value->[0]}); shift(@$value); while (@$value) { my $t=shift(@$value); my $v=shift(@$value); serialize($writer,$t,$v); } $writer->endTag(); } }

I am currently using XML::Writer and this 20 lines recursive sub to do the serialization. I'm sure I'm reinventing the wheel here but I can't find a module doing this.

Any hint?

TIA

Rule One: "Do not act incautiously when confronting a little bald wrinkly smiling man."

Replies are listed 'Best First'.
XML::LibXML
by ForgotPasswordAgain (Vicar) on Jul 11, 2008 at 14:13 UTC
    XML::LibXML can serialize XML:
        use XML::LibXML;
        my $parser = XML::LibXML->new();
    
        my $doc = eval { $parser->parse_file($file) };
        if ($@) {
            print STDERR "Couldn't parse '$file', skipping\n";
        } else {
            my $dom = $doc->documentElement;
    
            # use DOM methods here
    
            $doc->toFile($file);
        }
    
Re: Seralize a XML tree from XML::Parser
by Tanktalus (Canon) on Jul 11, 2008 at 15:26 UTC

    Reading, modifying, and spitting back out XML sounds like the default operation of XML::Twig... in fact, that was the first use I ever put XML::Twig to - modifying a small XML file to become a HUGE XML file (from a dozen or so KB to a few MB).