enum
并且Color
根据定义是可序列化的(用 装饰),因此序列化或属性SerializableAttribute
不应该有任何问题,请查看我的代码示例:enum
Color
public class Program
{
public static void Main()
{
using (var writer = XmlWriter.Create(Console.OpenStandardOutput()))
{
var telAvivProfile = new Profile
{
City = "Tel Aviv",
MaxTemp = 40,
MinTemp = 5,
ProfileColor = Color.FromRgb(4, 4, 4),
WeatherTypes = new List<WeatherType>
{
WeatherType.Sunny,
WeatherType.Rainy
}
};
var serializer = new XmlSerializer(telAvivProfile.GetType());
serializer.Serialize(writer, telAvivProfile);
Console.WriteLine(writer.ToString());
}
Console.ReadLine();
}
}
public enum WeatherType
{
Rainy,
Sunny,
Cloudy,
Windy
}
[Serializable]
[XmlRoot("Profile")]
public class Profile
{
public string ProfileName { get; set; }
public System.Windows.Media.Color ProfileColor { get; set; }
public string City { get; set; }
public double MinTemp { get; set; }
public double MaxTemp { get; set; }
public List<WeatherType> WeatherTypes { get; set; }
}
将为您生成以下 XML:
<?xml version="1.0" encoding="utf-8"?>
<Profile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ProfileColor="">
<A>255</A>
<R>4</R>
<G>4</G>
<B>4</B>
<ScA>1</ScA>
<ScR>0.001214108</ScR>
<ScG>0.001214108</ScG>
<ScB>0.001214108</ScB>
</ProfileColor>
<City>Tel Aviv</City>
<MinTemp>5</MinTemp>
<MaxTemp>45</MaxTemp>
<WeatherTypes>
<WeatherType>Sunny</WeatherType>
<WeatherType>Rainy</WeatherType>
</WeatherTypes>
</Profile>
此外,如果您想控制enum
字段的序列化方式,则可以使用XmlEnum
属性装饰每个字段,例如:
public enum WeatherType
{
[XmlEnum(Name="Hot")]
Rainy,
Sunny,
Cloudy,
Windy
}
以下是如何从文件反序列化/加载 XML:
Profile loadedProfile = null;
string path = "telAvivProfile.xml";
XmlSerializer serializer = new XmlSerializer(typeof (Profile));
StreamReader reader = new StreamReader(path);
loadedProfile = (Profile) serializer.Deserialize(reader);
reader.Close();