【问题标题】:XML Serialization Type ConverterXML 序列化类型转换器
【发布时间】:2013-10-15 11:52:56
【问题描述】:

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

【问题讨论】:

    标签: c# xml-serialization


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      相关资源
      最近更新 更多