I can't get a feel for either the size of primary_xml_snippet nor how many times it'll be called. My gut reaction is that this would be way cleaner as a regex find and replace, but if you're comfortable with this approach then go with it. I would like to see a unit test for this particular method though; it''d be much easier to pinpoint issues in it than testing it as part of the bigger test method below.