I was recently asked to troubleshoot some legacy code where an HTTPService call was (sometimes) failing on the server side due to malformed XML payload in a String parameter. On the client side, the XML was being created as a String from user input, which opened the door for invalid characters to be injected directly into the markup.
Rather than refactor the process that generates the XML altogether, I set out to see if there was a simple approach to simply escape the special characters and keep the rest of the String intact. I started to explore functions like HTMLEncode, thinking I could find functionality similar to what I needed.
Ultimately, the solution was far simpler.
It turns out that casting an XML-formatted String to an instance of the XML class handles special characters and performs all of the necessary logic to escape any offenders. So by simply constructing an XML object from the source String, then calling toString() on the XML object, we can effectively sanitize the original String into valid markup that can be parsed as expected.