JMK
JMK

Reputation: 28059

Representing Null values differently when serializing objects to XML

I am serializing objects to XML like so using the following code:

using System.IO;
using System.Xml.Serialization;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass thisClass = new MyClass() { One = "Foo", Two = string.Empty, Three = "Bar" };
            Serialize<MyClass>(thisClass, @"C:\Users\JMK\Desktop\x.xml");
        }

        static void Serialize<T>(T x, string fileName)
        {
            XmlSerializer v = new XmlSerializer(typeof(T));
            TextWriter f = new StreamWriter(fileName);
            v.Serialize(f, x);
            f.Close();
        }
    }

    public class MyClass
    {
        public string One { get; set; }
        public string Two { get; set; }
        public string Three { get; set; }
    }
}

This results in the following XML:

<?xml version="1.0" encoding="utf-8"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <One>Foo</One>
  <Two />
  <Three>Bar</Three>
</MyClass>

This is all well and good, apart from one thing. If one of my values is null, I can't omit this from the XML, it needs to be there, and I can't represent it as <Two />, instead I need to represent this as <Two></Two>.

Is this possible using my current method?

Upvotes: 2

Views: 2342

Answers (1)

Alex Kovanev
Alex Kovanev

Reputation: 1888

Using

[XmlElement(IsNullable = true)]
public string Two { get; set; }

you can represent it as <Two xsi:nil="true" />

Upvotes: 2

Related Questions