在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);
}
}
這兩種方法都可以確保在序列化和反序列化過程中正確處理特殊字符。