XML序列化类型转换器

时间:2013-10-15 11:52:56

标签: c# xml-serialization

在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”成为“真实”。

1 个答案:

答案 0 :(得分:4)

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

[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;}

相关问题