在 Json 中我可以这样做:
[JsonProperty("type")]
[JsonConverter(typeof(MyTpeConverter))]
public BoxType myType { get; set; }
.....
public class BoxTypeEnumConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
....
}
}
这在使用 XML 时是否也可行?
[XmlElement("isFolder")]
[XmlConvert()] // ???
public string IsFolder { get; set; }
我的 Xml 文件有例如
....
<isFolder>t</isFolder>
....
我希望“t”为“真”。
最佳答案
有两种方式: 简单的方法::)
[XmlElement("isFolder")]
public string IsFolderStr { get; set; }
[XmlIgnore]
public bool IsFolder { get{ ... conversion logic from IsFolderStr is here... }}
第二种方法是创建一个类来处理自定义转换:
public class BoolHolder : IXmlSerializable
{
public bool Value { get; set }
public System.Xml.Schema.XmlSchema GetSchema() {
return null;
}
public void ReadXml(System.Xml.XmlReader reader) {
string str = reader.ReadString();
reader.ReadEndElement();
switch (str) {
case "t":
this.Value = true;
...
}
}
并用 BoolHolder 替换属性的定义:
public BoolHolder IsFolder {get;set;}
关于c# - XML 序列化类型转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19380535/