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?