2

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?

Roee Adler
  • 33,434
  • 32
  • 105
  • 133

2 Answers2

3

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

Pavel Minaev
  • 99,783
  • 25
  • 219
  • 289
  • So WriteElementString is completely safe? (it makes sense when you say it, I just didn't know it was the case) – Roee Adler Jul 24 '09 at 05:19
  • It is "safe" in a sense that it guarantees that output will be valid XML, and that when you read it back, you'll get the same string. – Pavel Minaev Jul 24 '09 at 05:21
-2

You could safe these Values as CDATA that will be safest you can do with xml.

Prior you should check the values via RegEx or any other validation.

Oliver Friedrich
  • 9,018
  • 9
  • 42
  • 48