views:

612

answers:

2

Hello,

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?

+2  A: 

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

Pavel Minaev
So WriteElementString is completely safe? (it makes sense when you say it, I just didn't know it was the case)
Roee Adler
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
A: 

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.

BeowulfOF
Why the downvote? CDATA is safest way to hold you XML valid an contain everyting inside you wish?
BeowulfOF
CDATA does not matter at all. It's just a way to write text without needing to escape it. The code used by the OP will escape everything properly.
John Saunders
Written as CDATA it will not be escaped, but working properly.
BeowulfOF