在C#中,使用XML序列化時(shí),特殊字符會(huì)自動(dòng)進(jìn)行編碼和解碼
XmlTextWriter
或XmlTextReader
類。這些類會(huì)自動(dòng)處理特殊字符的編碼和解碼。using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
public class Program
{
public static void Main()
{
// 創(chuàng)建一個(gè)包含特殊字符的對(duì)象
Person person = new Person { Name = "張三", Age = 30 };
// 序列化對(duì)象到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字符串到對(duì)象
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反序列化后的對(duì)象:");
Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}");
}
}
[XmlRoot]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
SecurityElement.Escape
方法進(jìn)行編碼,使用SecurityElement.FromString
方法進(jìn)行解碼。using System;
using System.Security;
public class Program
{
public static void Main()
{
string input = "這是一個(gè)包含特殊字符的字符串:<>&\"'";
// 編碼特殊字符
string encoded = SecurityElement.Escape(input);
Console.WriteLine("編碼后的字符串:");
Console.WriteLine(encoded);
// 解碼特殊字符
string decoded = SecurityElement.FromString(encoded).Text;
Console.WriteLine("\n解碼后的字符串:");
Console.WriteLine(decoded);
}
}
這兩種方法都可以確保在序列化和反序列化過(guò)程中正確處理特殊字符。