XmlSerializer的属性转换 [英] XmlSerializer property converter

查看:116
本文介绍了XmlSerializer的属性转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose we have a class which can be serialized/deserialized by XmlSerializer. It would be like so:

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

我们有一个XML,这将是像这样:

We have an xml which will be like so:

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

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

Using of boolean property IsValid instead of string property is much better decision, but in this case we need to add some additional logic to convert data from string to bool.

简单而直接的方式来解决这个问题的方法是使用附加属性,并把一些转换逻辑到的IsValid吸气。

The simple and direct way to solve this problem is to use additional property and put some conversion logic into the IsValid getter.

任何人都可以提出一个更好的决定吗?要以某种方式的属性或类似的东西用一个类型转换器?

Can anyone suggest a better decision? To use a type converter in attributes somehow or something similar?

推荐答案

对待节点作为一个自定义类型:

Treat the node as a custom type:

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

您甚至可以作出这样的定制类结构代替,并提供它的隐式转换和布尔来使它更加透明。

You can even make that custom class a struct instead, and provide implicit conversions between it and bool to make it even more "transparent".

这篇关于XmlSerializer的属性转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆