Search code examples
c#.netxml-serializationxml-nil

Suppress xsi:nil but still show Empty Element when Serializing in .Net


I have a c# class that has 20+ string properties. I set about a fourth of those to an actual value. I would like to serialize the class and get an output of

<EmptyAttribute></EmptyAttribute>

for a property

public string EmptyAttribute {get;set;}

I do not want the output to be

<EmptyAttribute xsi:nil="true"></EmptyAttribute>

I am using the following class

public class XmlTextWriterFull : XmlTextWriter
{
    public XmlTextWriterFull(string filename) : base(filename,Encoding.UTF8) { }

    public override void WriteEndElement()
    {
        base.WriteFullEndElement();
        base.WriteRaw(Environment.NewLine);
    }
}

so that I can get the full tags. I just don't know how to get rid of the xsi:nil.


Solution

  • I was actually able to figure this out. I know its a bit of a hack in some ways but this is how I got it to work

     System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(header.GetType());
            XmlTextWriterFull writer = new XmlTextWriterFull(FilePath);
            x.Serialize(writer, header);
            writer.Flush();
            writer.BaseStream.Dispose();
            string xml = File.ReadAllText(FilePath);
            xml = xml.Replace(" xsi:nil=\"true\"", "");
            File.WriteAllText(FilePath, xml);
    

    Hope this helps someone else out