C# - XML反序列化属性

时间:2017-01-09 08:52:30

标签: c# xml serialization

我找不到没有getter的属性没有正确解析的原因,让我给你写一个例子:

格式化的XML

<request>
  <job 
     mode="modefirst"
  />
<request>

我正在尝试使用属性将其反序列化为POCO:

    private ESomeEnum emode;

    [XmlAttribute(AttributeName = "mode")]
    public string Mode
    {
       set { ESomeEnum.TryParse( blah blah );
    }

emode在类构造函数中被设置为默认值,而反序列化(没有自定义类的System.Xml.Serialization,只是在这里尝试简约)上面的xml,从不调用setter,但是当属性'模式'包含一个吸气剂

    get { return this.emode.ToString(); }

实际上,在反序列化过程中,setter被设置了正确的值。

为什么会出现这种情况?背后有什么理由吗?

1 个答案:

答案 0 :(得分:1)

XmlSerializer仅处理属性,它们具有公共get-set访问器。但您可以通过实施IXmlSerializable

来自定义任何内容
public class MyXmlSerializableClass : IXmlSerializable
{
    private ESomeEnum emode = ESomeEnum.modefirst;

    public string Mode
    {
        set { emode = ESomeEnum.Parse(value); }
    }

    public int ReadWriteProperty { get; set; }

    public int SemiReadOnlyProperty { get; private set; }

    private int backingFieldOfRealReadOnlyProperty;
    public int RealReadOnlyProperty
    {
        get { return backingFieldOfRealReadOnlyProperty; }
    }

    #region IXmlSerializable Members

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        throw new NotImplementedException();
    }

    public void ReadXml(XmlReader reader)
    {
        if (reader.Settings != null && !reader.Settings.IgnoreWhitespace)
        {
            reader = XmlReader.Create(reader, new XmlReaderSettings { IgnoreWhitespace = true });
            reader.Read();
        }

        reader.ReadStartElement();
        Mode = reader.ReadElementContentAsString("Mode", String.Empty);
        ReadWriteProperty = reader.ReadElementContentAsInt("ReadWriteProperty", String.Empty);
        SemiReadOnlyProperty = reader.ReadElementContentAsInt("ReadOnlyAutoProperty", String.Empty);
        backingFieldOfRealReadOnlyProperty = reader.ReadElementContentAsInt("ReadOnlyProperty", String.Empty);
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteElementString("Mode", emode.ToString());
        writer.WriteElementString("ReadWriteProperty", ReadWriteProperty.ToString(CultureInfo.InvariantCulture));
        writer.WriteElementString("ReadOnlyAutoProperty", SemiReadOnlyProperty.ToString(CultureInfo.InvariantCulture));
        writer.WriteElementString("ReadOnlyProperty", RealReadOnlyProperty.ToString(CultureInfo.InvariantCulture));
    }

    #endregion

    internal MyXmlSerializableClass()
    {/*needed for deserialization*/
    }
}