简体   繁体   中英

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 (eg 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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM