c# - XmlSerializer 属性转换器

标签 c# .net xml-serialization

假设我们有一个可以被 XmlSerializer 序列化/反序列化的类。应该是这样的:

[XmlRoot("ObjectSummary")]
public class Summary
{
     public string Name {get;set;}
     public string IsValid {get;set;}
}

我们有一个像这样的 xml:

<ObjectSummary>
   <Name>some name</Name>
   <IsValid>Y</IsValid>
<ObjectSummary>

使用 bool 属性 IsValid 而不是字符串属性是更好的决定,但在这种情况下,我们需要添加一些额外的逻辑来将数据从字符串转换为 bool 。

解决此问题的简单直接方法是使用附加属性并将一些转换逻辑放入 IsValid getter 中。

谁能提出更好的决定?以某种方式或类似的方式在属性中使用类型转换器?

最佳答案

将节点视为自定义类型:

[XmlRoot("ObjectSummary")]
public class Summary
{
    public string Name {get;set;}
    public BoolYN IsValid {get;set;}
}

然后在自定义类型上实现IXmlSerializable:

public class BoolYN : IXmlSerializable
{
    public bool Value { get; set }

    #region IXmlSerializable members

    public System.Xml.Schema.XmlSchema GetSchema() {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader) {
        string str = reader.ReadString();
        reader.ReadEndElement();

        switch (str) {
            case "Y":
                this.Value = true;
                break;
            case "N":
                this.Value = false;
                break;
        }
    }

    public void WriteXml(System.Xml.XmlWriter writer) {
        string str = this.Value ? "Y" : "N";

        writer.WriteString(str);
        writer.WriteEndElement();
    }

    #endregion
}

您甚至可以将该自定义类改为 struct,并在它和 bool 之间提供隐式转换以使其更加“透明”。

关于c# - XmlSerializer 属性转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5963423/

相关文章:

.net - 访问 .NET 服务时,WebORB 会增加什么值(value)?

c# - 如果没有子属性最终被序列化,避免向 xml 添加元素?

c# - C# 中 "this"赋值的示例是什么?

c# - 无法在.NET 3.5中使用ServiceController停止服务

c# - Windows Phone 中的 System.Collections.Generic.KeyNotFoundException

c# - 对象未将所有属性序列化为 XML

c# - 如何序列化包含 XML 属性的对象

c# - 可以在 API 上执行功能吗?

.net - 创建一个类型为字符串参数的对象

c# - 获取行号异常