我猜你遇到了编码问题,不是XMLReader
在XmlSerializer
.
您可以在以下代码段中使用XmlTextWriter
UTF8 编码和XmlSerializer
类似的编码(请参阅下面的通用方法以更好地实现它)。与变音符号 (äöü) 和其他特殊字符配合使用效果很好。
class Program
{
static void Main(string[] args)
{
SpecialCharacters specialCharacters = new SpecialCharacters { Umlaute = "äüö" };
// serialize object to xml
MemoryStream memoryStreamSerialize = new MemoryStream();
XmlSerializer xmlSerializerSerialize = new XmlSerializer(typeof(SpecialCharacters));
XmlTextWriter xmlTextWriterSerialize = new XmlTextWriter(memoryStreamSerialize, Encoding.UTF8);
xmlSerializerSerialize.Serialize(xmlTextWriterSerialize, specialCharacters);
memoryStreamSerialize = (MemoryStream)xmlTextWriterSerialize.BaseStream;
// converts a byte array of unicode values (UTF-8 enabled) to a string
UTF8Encoding encodingSerialize = new UTF8Encoding();
string serializedXml = encodingSerialize.GetString(memoryStreamSerialize.ToArray());
xmlTextWriterSerialize.Close();
memoryStreamSerialize.Close();
memoryStreamSerialize.Dispose();
// deserialize xml to object
// converts a string to a UTF-8 byte array.
UTF8Encoding encodingDeserialize = new UTF8Encoding();
byte[] byteArray = encodingDeserialize.GetBytes(serializedXml);
using (MemoryStream memoryStreamDeserialize = new MemoryStream(byteArray))
{
XmlSerializer xmlSerializerDeserialize = new XmlSerializer(typeof(SpecialCharacters));
XmlTextWriter xmlTextWriterDeserialize = new XmlTextWriter(memoryStreamDeserialize, Encoding.UTF8);
SpecialCharacters deserializedObject = (SpecialCharacters)xmlSerializerDeserialize.Deserialize(xmlTextWriterDeserialize.BaseStream);
}
}
}
[Serializable]
public class SpecialCharacters
{
public string Umlaute { get; set; }
}
我个人使用以下通用方法来序列化和反序列化 XML 和对象,并且还没有任何性能或编码问题。
public static string SerializeObjectToXml<T>(T obj)
{
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xmlSerializer.Serialize(xmlTextWriter, obj);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
string xmlString = ByteArrayToStringUtf8(memoryStream.ToArray());
xmlTextWriter.Close();
memoryStream.Close();
memoryStream.Dispose();
return xmlString;
}
public static T DeserializeXmlToObject<T>(string xml)
{
using (MemoryStream memoryStream = new MemoryStream(StringToByteArrayUtf8(xml)))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (StreamReader xmlStreamReader = new StreamReader(memoryStream, Encoding.UTF8))
{
return (T)xmlSerializer.Deserialize(xmlStreamReader);
}
}
}
public static string ByteArrayToStringUtf8(byte[] value)
{
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetString(value);
}
public static byte[] StringToByteArrayUtf8(string value)
{
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(value);
}