Esteemed Monks,

I just had to whip up a quick XML filtering prog to cleanup some nastily formatted XML files. Here's a quick snippet:
<?xml version="1.0"?> <!DOCTYPE VersionMaint PUBLIC "- EN" "http://path-to/the-dtd"> <VersionMaint> <MaintLevelInfo> <MaintId> </MaintId> </MaintLevelInfo> <MaintRequest> <AppId>987624</AppId> <AppName>TriggerVar</AppName> </MaintRequest> </VersionMaint>
The goal being to cleanup any empty block (in this example the MaintLevelInfo and MaintId blocks but there are more, sometimes 3 or 4 levels of empty blocks). The following code works but it just feels bad, I'm thinking there has to be a better way surely:
sub filterXML { my $xml = shift; my @xmlPieces = split (/\n/, $xml); my ($tmpFilter, $flag) = filter (\@xmlPieces); while ($flag) { ($tmpFilter, $flag) = filter ($tmpFilter); } my $filtered = join "\n", @$tmpFilter; return $filtered; } sub filter { my $items = shift; my (@new, $prev, $haveFiltered); for my $xmlLine (@$items) { my $test = $xmlLine; $test =~ s/^\s+//g; if ($test =~ /^<\// && $prev =~ /^<\w/) { unless ($prev =~ /<(.*)>(.*)<(.*)>/) { pop @new; $prev = $test; $haveFiltered++; next; } } push (@new, $xmlLine); $prev = $test; } return (\@new, $haveFiltered); }
Needless to say there's nothing I can do about the way the XML is originally formatted, I'm just the lucky fellow who has to fix it.

In reply to Cleaning Files by vek

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.