On a recent project, I had to use the SharePoint 2010 Lists web service (lists.asmx) to update list items using the UpdateListItems method which requires a Batch element (XmlNode) object to be created and passed into this method.
After creating the necessary XmlNode object to perform a Update on the list item, I kept receiving an error about some invalid characters.
First thing to check was the Xml Field element names were correct and didn't have any special characters. Everything looked fine. After debugging and looking at the attributes returned, I noticed an Xml element had a value of a URL and noticed an & character in the URL which is very common.
This is the most common illegal character when working with XML and most of the time I would replace it using the string class or use the URL encode method, so it is encoded as "&".
I happened to come across a method in the .NET framework after searching that I have never heard of before which was the perfect solution.
System.Security.SecurityElement.Escape(string fieldValue); will replace invalid xml characters in a string with their valid XML equivalent.
This was perfect, it handles the & and a few other characters to produce valid XML characters.
This method was such a simple solution to handle the XML strings, I can't believe I didn't know about this method before.