2

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?

1 Answer 1

2

Using

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't seem to change the XML at all, I have posted the exact code I am using above, I have just added [XmlElement(IsNullable = true)] above my second automatic property and I still get the same output.
Sorry if i misunderstood the problem. If you use the code above nothing will change in xml. You'll get xsi:nil if Two = null.
Ah of course, doh! I'm not sure if the people we are sending the file to will be happy with this either but I will give it a shot. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.