Reprezentowanie wartości Null inaczej podczas serializowania obiektów do XML
Serializuję obiekty do XML tak, używając następującego kodu:
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; }
}
}
Powoduje to następujący kod 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>
To wszystko jest dobre i dobre, z wyjątkiem jednej rzeczy. Jeśli jedna z moich wartości ma wartość NULL, nie mogę tego pominąć w XML, musi tam być i nie mogę jej przedstawić jako<Two />
, zamiast tego muszę to przedstawić jako<Two></Two>
.
Czy to możliwe przy użyciu mojej obecnej metody?