【问题标题】:Conditional usage of IXmlSerializable interface methodsIXmlSerializable 接口方法的条件使用
【发布时间】:2017-10-09 13:58:24
【问题描述】:

我需要一种以这种方式自定义C# XML(反)序列化机制的方法:

[Serializable]
public class MyElement : IXmlSerializable
{
    [XmlAttribute]
    public string PropertyX { get; set; }

    [XmlElement]
    public MySubElement SubElement { get; set; }

    // .... other properties and elements...

    [XmlIgnore]
    public string ElementXml { get;set; }


    public XmlSchema GetSchema() { return null; }

    public void ReadXml(XmlReader reader)
    {
        // use default deserialization mechanism, like IXmlSerializable isn't implemented
    }

    public void WriteXml(XmlWriter writer)
    {
        if (!string.IsNullOrEmpty(ElementXml)) {
            // serialize as ElementXml value
        }
        else 
        {
            // serialize using default serialization mechanism, like IXmlSerializable isn't implemented
        }
    }
}

我需要在多个元素上使用这个范例,例如 MySubElement 也应该像这样。对象模型很复杂,因此按属性或按元素实现此属性对我来说不是一个选项。 这个可以吗?

【问题讨论】:

标签: c# .net xml-serialization xmlserializer ixmlserializable


【解决方案1】:

考虑使用System.ComponentModel.DefaultValue 属性。

public class MyElement
{
    [XmlAttribute]
    public string PropertyX { get; set; }

    [XmlElement]
    public MySubElement SubElement { get; set; }

    [DefaultValue("")]
    public string ElementXml { get; set; }
}

如果ElementXmlstring.Empty,则不会被序列化。

你应该使用这样的代码:

private string _elementXml;

[DefaultValue("")]
public string ElementXml
{
    get => _elementXml;
    set => _elementXml = string.IsNullOrWhiteSpace(value) ? null : value;
}

在这种情况下,不仅不会被序列化为 null 或为空,也不会被序列化为任何空白字符串。

【讨论】:

  • 这解决了我的问题的哪一部分?跳过 ElementXml 序列化不是问题,我也可以使用 ShouldSerialize 方法做到这一点。我需要使用 cmets 解决部分代码。
  • @Filip - 它使用默认的序列化机制,没有 IXmlSerializable 实现。
猜你喜欢
  • 2011-03-11
  • 2010-10-28
  • 2010-09-21
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
  • 2017-06-19
  • 2012-05-01
  • 1970-01-01
相关资源
最近更新 更多