How to write an empty XML element with XmlWriter in c#

This is probably trivial to most of us, but sometimes it’s the simple stuff that is so easy to miss.

I have a class that converts an incoming flat file to XML and passes it to a payment system. If a field is missing, I thought I could just pass it null, but that didn’t work, because the system expected an attribute with the form:

<NewAccountNumber xsi:nil=”true“/>

I’m assuming you are familiar with an XmlWriter… Doing this turns out to be quite easy:

using System;
using System.Xml;
using System.Xml.Schema;

namespace Example
{
    public static class Extensions
    {
        public static void WriteEmptyElement(this XmlWriter writer, string name)
        {
            if (name == null)
                throw new ArgumentNullException("name");

            writer.WriteStartElement(name);
            try
            {
                writer.WriteAttributeString(
                    "xsi",
                    "nil",
                    XmlSchema.InstanceNamespace,
                    "true");
            }
            finally { writer.WriteEndElement(); }
        }
    }
}
Advertisements

About Jerome

I am a senior C# developer in Johannesburg, South Africa. I am also a recovering addict, who spent nearly eight years using methamphetamine. I write on my recovery blog about my lessons learned and sometimes give advice to others who have made similar mistakes, often from my viewpoint as an atheist, and I also write some C# programming articles on my programming blog.
This entry was posted in Programming and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s