在不实现 IXmlSerializable 的情况下,这几乎是您所能得到的(始终包含 Estimate 属性):
[XmlRoot("Val")]
public class DecimalField
{
[XmlText()]
public decimal Value { get; set; }
[XmlAttribute("Estimate")]
public bool Estimate { get; set; }
}
使用 IXmlSerializable,您的类看起来像这样:
[XmlRoot("Val")]
public class DecimalField : IXmlSerializable
{
public decimal Value { get; set; }
public bool Estimate { get; set; }
public void WriteXml(XmlWriter writer)
{
if (Estimate == true)
{
writer.WriteAttributeString("Estimate", Estimate.ToString());
}
writer.WriteString(Value.ToString());
}
public void ReadXml(XmlReader reader)
{
if (reader.MoveToAttribute("Estimate") && reader.ReadAttributeValue())
{
Estimate = bool.Parse(reader.Value);
}
else
{
Estimate = false;
}
reader.MoveToElement();
Value = reader.ReadElementContentAsDecimal();
}
public XmlSchema GetSchema()
{
return null;
}
}
您可以像这样测试您的课程:
XmlSerializer xs = new XmlSerializer(typeof(DecimalField));
string serializedXml = null;
using (StringWriter sw = new StringWriter())
{
DecimalField df = new DecimalField() { Value = 12.0M, Estimate = false };
xs.Serialize(sw, df);
serializedXml = sw.ToString();
}
Console.WriteLine(serializedXml);
using (StringReader sr = new StringReader(serializedXml))
{
DecimalField df = (DecimalField)xs.Deserialize(sr);
Console.WriteLine(df.Estimate);
Console.WriteLine(df.Value);
}