c# - XML 序列化类型转换器

标签 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”为“真”。

最佳答案

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

[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/

相关文章:

c# - 如何使用 protobuf-net 序列化和反序列化自定义列表

c# - 如何创建 C# 类模型来获取给定格式的 XML 序列化请求?

java - 多读取器文件java

c# - 由于 dll 不同,克隆/序列化会产生错误的类

c# - 在没有序列化的情况下克隆对象

c# - .Net XML 序列化问题

c# - 处理 ASP.NET 空 Web 应用程序上的所有请求

c# - Xamarin Forms Listview 的条目与自定义选择器冲突

c# - 为什么我应该从设计器中插入一个非 UI Windows.Forms 组件?

c# - 为什么方法重载在此 C# 程序中不起作用?