简体   繁体   English

C#:使用XmlTextWriter消毒XML文本值?

[英]C#: Sanitize XML text values with XmlTextWriter?

I'm using XmlTextWriter to serialize and persist some of my data. 我正在使用XmlTextWriter序列化并保留一些数据。 Several of the fields I serialize are based on user input (eg Username). 我序列化的几个字段基于用户输入(例如,用户名)。 Today I use the WriteElementString method of XmlTextWriter . 今天,我使用XmlTextWriterWriteElementString方法。

My question is: the second parameter of WriteElementString is the text value to be written. 我的问题是: WriteElementString的第二个参数是要写入的文本值。 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. 变量inputUserNameinputEmail是用户输入的,我想在编写之前清理/转义它们。

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) WriteElementString可以完成XML所需的所有转义操作(即& -> &amp;< -> &lt;等)

You could safe these Values as CDATA that will be safest you can do with xml. 您可以将这些值作为CDATA来保护,这对于xml来说是最安全的。

Prior you should check the values via RegEx or any other validation. 在此之前,您应该通过RegEx或任何其他验证检查值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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