views:

15

answers:

0

I would like to create a simple parser class for Silverlight which parses this text:

[size=15]This is the header[/size]

This is [i]italicized text[/i] and this is [b]bolded text[/b] and this is a hyperlink: [url]http://example.org[/url] and so is this: [url=http://example.com]Example[/url].

into this kind of code:

TextBlock tb = new TextBlock();
tb.FontSize = 15;

Run run1 = new Run();
run1.Text = "This is ";

Run run2 = new Run();
run2.FontStyle = FontStyles.Italic;
run2.Text = "italicized text";

Run run3 = new Run();
run3.Text = " and this is ";
...

tb.Inlines.Add(run1);
tb.Inlines.Add(run2);
tb.Inlines.Add(run3);
...

My approach would be to create a class called TextTree with a List and first run through the string character by character looking for known bbcode tags and filling the TextTree collection with TextPart objects which have properties indicating if that text part should be italic, bold, etc. Then iterate through the TextTree collection building the TextBlock and filling it with appropriate Run objects.

I realize, however, that this is a quite simple approach which is not very scalable i.e. it would be difficult to later handle text such as:

This text is [b]bold and [i]this is also italic with a [url=http://google.com]hyperlink[/url] in it[/i][/b].

What would be a better "parsing pattern" to use which would be more scalable, i.e. able to handle embedded tags?