在C#中,使用XML序列化时,特殊字符会自动进行编码和解码
- 使用
XmlTextWriter
或XmlTextReader
类。这些类会自动处理特殊字符的编码和解码。
using System; using System.IO; using System.Xml; using System.Xml.Serialization; public class Program { public static void Main() { // 创建一个包含特殊字符的对象 Person person = new Person { Name = "张三", Age = 30 }; // 序列化对象到XML字符串 string xmlString; using (StringWriter stringWriter = new StringWriter()) { XmlSerializer serializer = new XmlSerializer(typeof(Person)); using (XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter)) { serializer.Serialize(xmlTextWriter, person); } xmlString = stringWriter.ToString(); } Console.WriteLine("序列化后的XML字符串:"); Console.WriteLine(xmlString); // 反序列化XML字符串到对象 Person deserializedPerson; using (StringReader stringReader = new StringReader(xmlString)) { XmlSerializer serializer = new XmlSerializer(typeof(Person)); using (XmlTextReader xmlTextReader = new XmlTextReader(stringReader)) { deserializedPerson = (Person)serializer.Deserialize(xmlTextReader); } } Console.WriteLine("\n反序列化后的对象:"); Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}"); } } [XmlRoot] public class Person { public string Name { get; set; } public int Age { get; set; } }
- 如果需要手动处理特殊字符,可以使用
SecurityElement.Escape
方法进行编码,使用SecurityElement.FromString
方法进行解码。
using System; using System.Security; public class Program { public static void Main() { string input = "这是一个包含特殊字符的字符串:<>&\"'"; // 编码特殊字符 string encoded = SecurityElement.Escape(input); Console.WriteLine("编码后的字符串:"); Console.WriteLine(encoded); // 解码特殊字符 string decoded = SecurityElement.FromString(encoded).Text; Console.WriteLine("\n解码后的字符串:"); Console.WriteLine(decoded); } }
这两种方法都可以确保在序列化和反序列化过程中正确处理特殊字符。