XML 序列化和反序列化 c# 中的列表<字符串>
本文关键字:列表 字符串 序列化 反序列化 XML | 更新日期: 2023-09-27 18:36:35
我有一个跟随类的对象
[XmlRoot("http://schemas.abc.com")]
[DataContract]
public class Employee
{
[XmlAttribute]
[DataMember]
public List<string> Positions { get; set; }
}
职位包含以下两个字符串"项目经理"和"高级项目经理"
我通过以下方法序列化了这个对象并保存在数据库中
public static string Serialize(Employee entity)
{
var memoryStream = new MemoryStream();
var serializer = new XmlSerializer(typeof(Employee));
using (var xmlTextWriter = new XmlTextWriter(memoryStream,
Encoding.Unicode))
{
serializer.Serialize(xmlTextWriter, entity);
xmlTextWriter.Close();
}
return UnicodeByteArrayToString(memoryStream.ToArray());
}
private static string UnicodeByteArrayToString(byte[] input)
{
var constructedString = Encoding.Unicode.GetString(input);
return constructedString;
}
然后我通过以下方法检索和反序列化对象
public static Employee Deserialize(string str)
{
var data = StringToUnicodeByteArray(str);
var memoryStream = new MemoryStream(data);
var serializer = new XmlSerializer(typeof(Employee));
var xmlTextReader = new XmlTextReader(memoryStream);
return (Employee)serializer.Deserialize(xmlTextReader);
}
private static byte[] StringToUnicodeByteArray(string input)
{
var byteArray = Encoding.Unicode.GetBytes(input);
return byteArray;
}
现在我在位置列表中获得了 5 个字符串对象
"项目"、"经理"、"高级"、"项目"、"经理"反序列化是在每个空格后创建新的字符串对象
快速帮助将不胜感激
Eugene Podskal 的答案
认为您应该删除 XmlAttribute 属性。XmlSerializer 不知道如何分析属性字符串中的值,除了在空格上拆分它。或者,您可以创建一个属性,该属性将为您提供 String,该字符串允许明确分隔其中的各个项目(例如逗号或其他任何内容),并且可以从它设置为的字符串中解析单个项目。此属性是可序列化的,而实际列表将是 XmlIgnore