Representing Null values differently when serializing objects to XML

Axomporygoozy

New Member
I am serializing objects to XML like so using the following code:\[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; } }}\[/code\]This results in the following XML:\[code\]<?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>\[/code\]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 \[code\]<Two />\[/code\], instead I need to represent this as \[code\]<Two></Two>\[/code\].Is this possible using my current method?Thanks
 
Back
Top