XmlSerializer属性转换器

mad*_*ree 12 .net c# xml-serialization

假设我们有一个可以由XmlSerializer序列化/反序列化的类.它会是这样的:

[XmlRoot("ObjectSummary")]
public class Summary
{
     public string Name {get;set;}
     public string IsValid {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

我们有一个xml,如下所示:

<ObjectSummary>
   <Name>some name</Name>
   <IsValid>Y</IsValid>
<ObjectSummary>
Run Code Online (Sandbox Code Playgroud)

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

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

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

Jor*_*eda 14

将节点视为自定义类型:

[XmlRoot("ObjectSummary")]
public class Summary
{
    public string Name {get;set;}
    public BoolYN IsValid {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

然后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
}
Run Code Online (Sandbox Code Playgroud)

您甚至可以struct改为创建自定义类,并在它之间提供隐式转换,使其bool更加"透明".

  • 好答案。但是,我必须删除语句writer.WriteEndElement();。以防止在serializer.Serialize(...)操作期间崩溃 (2认同)

Ali*_*tad 8

我这样做的方式 - 这是次优的,但没有找到更好的方法 - 是定义两个属性:

[XmlRoot("ObjectSummary")]
public class Summary
{
     public string Name {get;set;}
     [XmlIgnore]
     public bool IsValid {get;set;}
     [XmlElement("IsValid")]
     public string IsValidXml {get{ ...};set{...};}

}
Run Code Online (Sandbox Code Playgroud)

用简单代码替换...以读取和写入IsValid值到Y和N并从中读取.