【发布时间】:2016-06-30 15:36:45
【问题描述】:
我正在使用XmlSerializer 将class 输出到.xml 文件。在大多数情况下,这是按预期和预期工作的。但是,作为一项要求,需要从数据的值中删除某些字符,并用其正确的转义字符替换。
在我需要替换值的元素中,我使用Replace() 方法并返回更新后的字符串。下面的代码显示了这个字符串替换;注释掉的行是因为 XmlSerializer 已经转义了那些特定的字符。
当&、<、>、' 和" 字符出现在 XML 元素的值中时,我有第三方的要求。目前&、< 和> 字符正通过XmlSerializer 进行适当转义。
出现这些字符时收到的错误是:
我们的系统在请求消息附件中检测到潜在威胁。
但是,当我在执行字符串替换后序列化 XML 文档时,XmlSerializer 会在&amp;apos; 中看到& 字符并将其变为&amp;apos;。我认为这是XmlSerializer 对象的正确功能。但是,我希望序列化程序 a.) 忽略转义字符;或 b.) 序列化其他需要转义的字符。
谁能解释一下,具体来说,如何完成其中任何一个?
字符串替换方法
public static string CheckValueOfProperty(string str)
{
string trimmedString = str.Trim();
if (string.IsNullOrEmpty(trimmedString))
return null;
else
{
// Commented out because the Serializer already transforms a '&' character into the appropriate escape character.
//trimmedString = trimmedString .Replace("&", "&");
//trimmedString = trimmedString.Replace("<", "<");
//trimmedString = trimmedString.Replace(">", ">");
trimmedString = trimmedString.Replace("'", "'");
trimmedString = trimmedString.Replace("\"", """);
return trimmedString;
}
}
XmlSerializer 代码
public static void SerializeAndOutput(object obj, string outputFilePath, XmlSerializerNamespaces ns = null)
{
XmlSerializer x = new XmlSerializer(obj.GetType());
// If the Output File already exists, delete it.
if (File.Exists(outputFilePath))
{
File.Delete(outputFilePath);
}
// Then, Create the Output File and Serialize the parameterized object as Xml to the Output File
using (TextWriter tw = File.CreateText(outputFilePath))
{
if (ns == null)
{
x.Serialize(tw, obj);
}
else { x.Serialize(tw, obj, ns); }
}
// =====================================================================
// The code below here is no longer needed, was used to force "utf-8" to
// UTF-8" to ensure the result was what was being expected.
// =====================================================================
// Create a new XmlDocument object, and load the contents of the OutputFile into the XmlDocument
// XmlDocument xdoc = new XmlDocument() { PreserveWhitespace = true };
// xdoc.Load(outputFilePath);
// Set the Encoding property of each XmlDeclaration in the document to "UTF-8";
// xdoc.ChildNodes.OfType<XmlDeclaration>().ToList().ForEach(d => d.Encoding = "UTF-8");
// Save the XmlDocument to the Output File Path.
// xdoc.Save(outputFilePath);
}
【问题讨论】:
标签: c# xmlserializer