Prevent serializing empty elements

Jan 29, 2013 at 10:48 PM

I'm looking for a way to prevent properties from being serialized when they are empty/null.

What is the recommend way to do this?

I tried using the GeneratePropertyNameSpecified, but when using this approach there appears to be additional code needed to set the specified property to true as the generated code does not have logic to set it to true when the property is set.

Feb 20, 2013 at 3:51 PM
I also need to know this.
Feb 20, 2013 at 4:17 PM
For now I have a helper routine to process the XML and remove empty nodes.
    public static XDocument RemoveEmptyNodes(XDocument xdoc)
    {
        if (xdoc == null)
            return null;

        xdoc.Descendants()
                .Where(e => e.IsEmpty || String.IsNullOrWhiteSpace(e.Value))
                .Remove();

        return xdoc;
    }
Feb 20, 2013 at 4:21 PM
Edited Feb 20, 2013 at 4:22 PM
HaroldHenry wrote:
For now I have a helper routine to process the XML and remove empty nodes.
    public static XDocument RemoveEmptyNodes(XDocument xdoc)
    {
        if (xdoc == null)
            return null;

        xdoc.Descendants()
                .Where(e => e.IsEmpty || String.IsNullOrWhiteSpace(e.Value))
                .Remove();

        return xdoc;
    }
VB.NET equivalent
Public Shared Function RemoveEmptyNodes(xdoc As XDocument) As XDocument
    If xdoc Is Nothing Then
        Return Nothing
    End If

    xdoc.Descendants().Where(Function(e) e.IsEmpty OrElse [String].IsNullOrWhiteSpace(e.Value)).Remove()

    Return xdoc
End Function
Just posted that for relevancy. So what exactly are you passing into that parameter? The serialized object?