Imagine you have a huge XML. It has some header, then a <Foos> tag full of <Foo> tags and nothing more. And you have a tool that's able to somehow process such XML if only it either contained just one <Foo> or at least was not so big. Here is a tiny script that allows you to specify the name of the <Foo> tag, the huge file and floods your disk with little files containing one <Foo> each:

use strict; use warnings; no warnings 'uninitialized'; use XML::Rules; die "Usage: $0 split_tag filename(s)\n" unless @ARGV >= 2; my ($split_tag, @files) = @ARGV; my $parser = XML::Rules->new( rules => [ _default => 'raw', $split_tag => sub { my ($file, $id) = ( $_[4]->{parameters}{'file'}, ++$_[4]-> +{parameters}{'id'}); $id = sprintf "%04d", $id; $file =~ s/(?:\.xml)?$/-$id.xml/i; if (ref $_[3]->[-1]{_content}) { $_[3]->[-1]{_content}[-1] =~ s/^.*(\n[^\n]+)$/$1/s; } else { $_[3]->[-1]{_content} =~ s/^.*(\n[^\n]+)$/$1/s; } print " $file\n"; open my $FH, '>:utf8', $file or die qq{Can't create "$file +": $^E\n}; print $FH $_[4]->parentsToXML(); print $FH $_[4]->ToXML( $_[0], $_[1]),"\n"; print $FH $_[4]->closeParentsToXML(); close $FH; return; } ] ); foreach my $file (@files) { $parser->parsefile( $file, {file => $file}); }

That's it folks ;-)

And you only ever have the header plus one <Foo> in memory. Of course if you wanted to get rid of the <Foos>, rename the <Foo> or something, you can add that.


In reply to Split XML to chunks by Jenda

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.