假设我们有一个可以被 XmlSerializer 序列化/反序列化的类。应该是这样的:
[XmlRoot("ObjectSummary")]
public class Summary
{
public string Name {get;set;}
public string IsValid {get;set;}
}
我们有一个像这样的 xml:
<ObjectSummary>
<Name>some name</Name>
<IsValid>Y</IsValid>
<ObjectSummary>
使用 bool 属性 IsValid 而不是字符串属性是更好的决定,但在这种情况下,我们需要添加一些额外的逻辑来将数据从字符串转换为 bool 。
解决此问题的简单直接方法是使用附加属性并将一些转换逻辑放入 IsValid getter 中。
谁能提出更好的决定?以某种方式或类似的方式在属性中使用类型转换器?
最佳答案
将节点视为自定义类型:
[XmlRoot("ObjectSummary")]
public class Summary
{
public string Name {get;set;}
public BoolYN IsValid {get;set;}
}
然后在自定义类型上实现IXmlSerializable
:
public class BoolYN : IXmlSerializable
{
public bool Value { get; set }
#region IXmlSerializable members
public System.Xml.Schema.XmlSchema GetSchema() {
return null;
}
public void ReadXml(System.Xml.XmlReader reader) {
string str = reader.ReadString();
reader.ReadEndElement();
switch (str) {
case "Y":
this.Value = true;
break;
case "N":
this.Value = false;
break;
}
}
public void WriteXml(System.Xml.XmlWriter writer) {
string str = this.Value ? "Y" : "N";
writer.WriteString(str);
writer.WriteEndElement();
}
#endregion
}
您甚至可以将该自定义类改为 struct
,并在它和 bool
之间提供隐式转换以使其更加“透明”。
关于c# - XmlSerializer 属性转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5963423/