【问题标题】:Only output XML elements that are set when serializing仅输出序列化时设置的 XML 元素
【发布时间】:2016-09-01 14:32:04
【问题描述】:

我有以下 XML:

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

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

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

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

是否需要 XSD?如果是,我会怎么做?

【问题讨论】:

  • 在上面的例子中,itemquantity do 有值...

标签: c# xml serialization xml-serialization


【解决方案1】:

对于简单的情况,您通常可以使用[DefaultValue] 让它忽略元素。对于更复杂的情况,您可以添加任何成员 Foo(属性/字段):

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

【讨论】:

  • "DefaultValue" 成功了,也很高兴看到其他技术的属性。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
  • 2015-06-13
  • 2010-11-10
  • 2011-06-24
相关资源
最近更新 更多