只输出序列化时设置的XML个元素

Only output XML elements that are set when serializing

我有以下 XML:

<Line id="6">
  <item type="product" />
  <warehouse />
  <quantity type="ordered" />
  <comment type="di">Payment by credit card already received</comment>
</Line>

在.NET (2010 with C#) 中序列化对象时,有没有办法不输出未设置的元素?在我的例子中,item typewarehousequantity 这样我在序列化时得到以下结果:

<Line id="6">
  <comment type="di">Payment by credit card already received</comment>
</Line>

我在 XmlElement 或 XmlAttribute 中看不到任何可以让我实现此目的的属性。

是否需要XSD?如果是,我该怎么办?

对于简单的情况,通常可以使用[DefaultValue]让它忽略元素。对于更复杂的情况,然后对于任何 member Foo (属性 / field) 你可以添加:

public bool ShouldSerializeFoo() {
    // TODO: return true to serialize, false to ignore
}
[XmlElement("someName");
public string Foo {get;set;}

这是许多框架和序列化程序支持的基于名称的约定。

例如,这只写 AD:

using System;
using System.ComponentModel;
using System.Xml.Serialization;

public class MyData {
    public string A { get; set; }
    [DefaultValue("b")]
    public string B { get; set; }
    public string C { get; set; }

    public bool ShouldSerializeC() => C != "c";

    public string D { get; set; }

    public bool ShouldSerializeD() => D != "asdas";

}
class Program {
    static void Main() {
        var obj = new MyData {
            A = "a", B = "b", C = "c", D = "d"
        };
        new XmlSerializer(obj.GetType())
            .Serialize(Console.Out, obj);
    }
}

B[DefaultValue]而省略; C 被省略,因为 ShouldSerializeC 返回 false