1

在 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”是“真的”。

4

1 回答 1

5

有两种方法:简单的方法::)

[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 替换属性的定义:

公共 BoolHolder IsFolder {get;set;}

于 2013-10-15T12:09:28.173 回答