If you could post a sample project that demonstrates the problem, it would be much easier to help debug.
Some places to start looking:
- check that the XML being passed in is correctly formed.
- check that the definitions for the blocks in your workspace have been loaded in JS prior to calling the code snippet.
I'd also try hardcoding a very basic workspace XML to see if that runs through that code snippet. Then, assuming that works successfully, slowly add block XML to eventually match the XML that's causing problems.