Prettification of XML - .NET 2.0 partial classes

I wrote about prettification of XML in Web Services earlier, and described how you can prettify your XML by modifying the generated code.  As Ram points out, in .NET 2.0, you can use partial classes for a cleaner way to add the XmlNamespaceDeclarations into your classes, without modifying the code.

The approach I described involved modifying the source files that were generated from .xsd's. This is obviously tricky, especially in an automated build. Changes to the XSD should occur only rarely, but still, there is a "then a miracle happens" step in your automated build where you have to grab the generated file and manually insert code into it.

Ram says:

But, if you are using .NET 2.0, then you can implement this pattern in a cleaner way using partial classes. Xsd.exe will generate a partial class for Address and other types defined in the schema.

You can define another file called AddressEx.cs, copy the following code and add the file to project. This way you don’t have to edit the files generated by xsd.exe. In fact, you can write a simple tool to generate this file. This works like a charm.

Great point, Ram. If that weren't enough, here's some sample code he provided:

using System;

using System.Collections.Generic;

using System.Text;

using System.Xml.Serialization;

 

partial class Address

{

    public Address()

    {

        namespaces.Add("b", "urn:my-enterprise:Basics");

    }

 

    [XmlNamespaceDeclarations]

    public XmlSerializerNamespaces namespaces =

      new XmlSerializerNamespaces();

 

}

That would all be in a separate, standalone file, which wouldn't have to change when the XSD changes.

Partial classes in C# 2.0 are nice in lots of different scenarios. ASP.NET 2.0 uses this feature very broadly. Find out more about partial classes here.

-Dino