4

I'm trying to write a perl script that removes whitespace from XML tags, but leaves whitespace inside of the values. For example, let's say I have:

<Example>This is an example.</Exampl   e>

What I'm looking to accomplish is to knock off the whitespace specifically in </Exampl e>. Since this will be working on an entire XML document, I figured I'd do something with the substitution operator, but I can't quite figure out how to only match whitespace that might be inside of the XML tags themselves.

Any help is greatly appreciated!

Edit: I've added a real example of what is occurring:

not well-formed (invalid token) at line 42, column 25, byte 1456:
                    <Artist>Eminem</Artist>
                    <FileName>eminem feat lil wayne - no love -
hotnewhiphop com(2).mp3</    FileName>
========================^
                    <FileSize>4804478</FileSize>
4
  • 1
    Based on this example, the XML might not be well-formed. Is that correct? (That makes a big difference to the approach needed.) Aug 2, 2011 at 16:36
  • Correct, the problem occurs after I decode a quoted print message that contains the xml data. However, there should not be any spaces in the tags themselves based on the schema being used.
    – Timothy
    Aug 2, 2011 at 16:54
  • 1
    How are you doing the decoding? Are you doing this manually or using CPAN's MIME-tools (i.e., MIME::Decoder)? -- It's always better to avoid getting stuff broken in the first place, rather than trying to patch it afterwards Aug 2, 2011 at 18:18
  • I'm using MIME::QuotedPrint::Perl's decode to handle the file, and it cleans it up (otherwise you see =20's on the end of some lines). It'd be nice if I could tell the RIAA to clean up their XML, but I doubt they'd be cooperative.
    – Timothy
    Aug 2, 2011 at 18:30

2 Answers 2

3
s!(</?\w+)\s+(\w+\s+/?>)!$1$2!g;

If you want to actually leave whitespace in a tag with attributes, it gets more complex, because whitespace is a legitimate character in a tag. You pretty much have to find the "words" with no equals or space + equals after them and marry them to the previous--unquoted--word.

sub marry_inner_splits {
    my $_ = shift;
    # fix broken tags
    s|^/?(\w+)\s+(\w+)\b(?!\s*=)|$1$2|; 
    # find the resulting position.
    my $pos = index( $_, ' ' );
    # return if there is no whitespace.
    return $_ if $pos == -1;
    # bind the rest of the text to the substring
    substr( $_, $pos ) =~ s/(\s*\w+)\s+(\w+\s*=\s*(?:"[^"]+"|'[^']+')\s*)/$1$2/g;
    return $_;
}

my $tag_str = q{Some stuff before the tag <ta g attr1="val1" att   r2="value #2"     /></Escap   e>};
$tag_str =~ s/<([^>]+)>/'<' . marry_inner_splits($1) . '>'/ge;

The e flag means that you are*eval*-ing in the replacement part.

2
  • There are boolean attributes (without values), eg <input type="checkbox" checked name="foo"/>
    – Qtax
    Aug 2, 2011 at 18:12
  • Qtax, then it is not XML. In XML all attributes must have quoted values.
    – Axeman
    Aug 2, 2011 at 20:49
1

I'd strongly recommend avoiding rolling your own XML parsing, or trying to manipulate the XML via regexes etc.

Use one of the many XML parsers available, and save yourself the headaches.

For instance, look at XML::Easy, XML::Smart, XML::TreeBuilder, XML::Twig.

See also http://perl-xml.sourceforge.net/faq/ for a pretty comprehensive FAQ on handling XML with Perl.

5
  • 1
    If it's not well formed, reject it, rather than trying to munge it in nasty ways which will be prone to fragility and unexpected breakage. Aug 2, 2011 at 16:44
  • And that's the problem I keep running into. I'm trying to parse DMCA notifications from various sources (that seem to like using quoted print messages that mess up the XML itself) Every time I try to parse certain XML documents I receive, I get invalid token caused by not well-formed XML tags, which I'm trying to fix. Will any of those modules fix that or interpret white space intelligently?
    – Timothy
    Aug 2, 2011 at 16:49
  • 1
    You could try running the XML through e.g. xmllint and see what it makes of it. Generally speaking, I'd rather stand by the "if it's not valid XML, reject it" approach, though. Aug 2, 2011 at 16:54
  • 2
    @Timothy, Sounds like you're saying you're not properly handling the transfer (or some such) encoding. Perhaps that's what we should be looking at?
    – ikegami
    Aug 2, 2011 at 16:59
  • Essentially what happens is, I have to strip quoted print from a mail message containing XML using MIME::QuotedPrint::Perl, which usually works, except that some of the e-mails look like they line wrapped the text and split some tags across lines or added whitespace.
    – Timothy
    Aug 2, 2011 at 17:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.