Search code examples
c#xmlescapingsanitizationxmltextwriter

C#: Sanitize XML text values with XmlTextWriter?


I'm using XmlTextWriter to serialize and persist some of my data. Several of the fields I serialize are based on user input (e.g. Username). Today I use the WriteElementString method of XmlTextWriter.

My question is: the second parameter of WriteElementString is the text value to be written. How can I sanitize it prior to writing?

An example code:

XmlTextWriter writer = new XmlTextWriter("filename.xml", null);

writer.WriteStartElement("User");
writer.WriteElementString("Username", inputUserName);
writer.WriteElementString("Email", inputEmail);
writer.WriteEndElement();

writer.Close();

The variables inputUserName and inputEmail are user-input, and I would like to sanitize/escape them prior to writing.

What's the best way to achieve this?


Solution

  • What exactly do you need to escape there? WriteElementString will do all escaping needed by XML already (i.e. & -> &amp;, < -> &lt;, etc)