If I understand things right you just need to overcome the stupid decision of the XML specification authors to require that a XML file is all onclosed in a single tag effectively preventing appending to XML files, right?

One solution would be to leave of the closing marker from the file as it's being appended to and only add it whenever you need to read it. The other would be to open the file in <+ mode, seek to a position a few bytes before the end and write the data and the closing tag.

my $marker = "<marker>\n"; my $endmarker = "</marker>\n"; my $marker_length = length($endmarker); $marker_length++ if $^O =~ /MSWin/; # because of the \n -> CRLF conver +sion sub append { my ($file, $data) = @_; if (!-s $file) { open my $FH, '>', $file or die qq{Can't open "$file" : $^E\n}; print $FH $marker, $data, $endmarker; close $FH; } else { open my $FH, '+<', $file or die qq{Can't open "$file" : $^E\n} +; seek $FH, -$marker_length, 2; print $FH $data, $endmarker; close $FH; } } append('text.xml', "<foo>ahoj</foo>\n"); append('text.xml', "<foo>cau</foo>\n"); append('text.xml', "<foo>co</foo>\n"); append('text.xml', "<foo>delas?</foo>\n");

I did not include any locking so that it doesn't obscure the solution. You should definitely add it.


In reply to Re: Appending a file between XML markers by Jenda
in thread Appending a file between XML markers by juan_in_nippon

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.