C# XML序列化怎樣處理特殊字符

c#
小樊
98
2024-09-14 21:22:29

在C#中,使用XML序列化時(shí),特殊字符會(huì)自動(dòng)進(jìn)行編碼和解碼

  1. 使用XmlTextWriterXmlTextReader類。這些類會(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; }
}
  1. 如果需要手動(dòng)處理特殊字符,可以使用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ò)程中正確處理特殊字符。

0