I have the following XML:
<Line id="6">
<item type="product" />
<warehouse />
<quantity type="ordered" />
<comment type="di">Payment by credit card already received</comment>
</Line>
Is there a way to not output the elements that aren't set when serializing an object in .NET (2010 with C#)? In my case, the item type
, the warehouse
, the quantity
so that I end up with the following instead when serialized:
<Line id="6">
<comment type="di">Payment by credit card already received</comment>
</Line>
I can't see any properties in the XmlElement or XmlAttribute that would let me achieve this.
Is XSD required? If it is, how would I go about it?
For simple cases, you can usually use [DefaultValue]
to get it to ignore elements. For more complex cases, then for any member Foo
(property / field) you can add:
public bool ShouldSerializeFoo() {
// TODO: return true to serialize, false to ignore
}
[XmlElement("someName");
public string Foo {get;set;}
This is a name-based convention supported by a number of frameworks and serializers.
For example, this writes just A
and D
:
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
is omitted because of [DefaultValue]
; C
is omitted because of the ShouldSerializeC
returning false
.