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

Hello,

I'm attempting to parse XML files with Parse::RecDescent. I'm trying to implement all of the productions described in the XML Spec. I'm concerned about production 14

The production is: [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)

Here's what I've implemented for my P::RD grammar:

CharData : /[^<&]*/ { my $s = $item[1]; if($s =~ /(.*)(]]>.*)/s) { $s = $1; $text = $2 . $text; Parse::RecDescent::LineCounter::resync($thisline); } $return = XML::CharData->new($s); }

Note: The class XML::CharData is my own creation.

Could some of you help review this implementation? Is this the correct/best way to implement production 14? It seems to work OK in my unit tests, but it seems very inefficient because it may read a lot of extra data until it hits an "&" or "<".

Thanks, Glen Hein

Replies are listed 'Best First'.
Re: P:RD and XML (minor code review)
by ikegami (Patriarch) on Feb 17, 2010 at 16:15 UTC

    I'm attempting to parse XML files with Parse::RecDescent

    Gotta ask why!

    Anyway, Perl can handle that with zero-width lookaheads.

    CharData : /(?:(?!\]\]>)[^<&])*/ { XML::CharData->new($item[1]) }
    or
    CharData : /(?:(?!<|&|\]\]>).)*/ { XML::CharData->new($item[1]) }
    or
    CharData : /(?:[^<&\]]|\](?!\]>))*/ { XML::CharData->new($item[1]) }

      Why, you ask? The short answer is for shits-n-giggles :-) I wanted to learn more about P::RD, and I wanted to study the finer details of the XML spec. I don't plan on using my XML parser for anything more than a learning exercise.

      Thanks for for suggestions. I've never played with the zero-width regular expressions. I'll have to experiment with them.

      BTW, I didn't mean to post as Anonymous. I thought I was logged in when I posted, by I guess I wasn't!