2

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?

1
  • in the example above, though, item and quantity do have values... Commented Sep 1, 2016 at 14:34

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

"DefaultValue" did the trick and also great to see the other technique with the properties. Many thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.