Depending on what your markup looks like, you might get some interesting ideas about how to tackle this problem from
Why I like functional programming. Or not - what is discussed there is rather different from any normal concept of a grammar or parsing.