Udostępnij za pośrednictwem


Prettification of XML - .NET 2.0 partial classes

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

Comments

  • Anonymous
    February 09, 2006
    Many thanks for this, its saved an awful headache where we thought we were going to have to add the namespaces using XSL :s
    I had found how to do it when manually serializing (using XmlSerializerNamespaces) but just needed this final step.
    On a side note, I have found the new WSDL.exe in VS2005 much more reliable for contract first web service development than the old one. It beats all other tools I could find IMHO. Cheers again!
  • Anonymous
    August 06, 2008
    Prettification of XML Serialization within Web Services This came up yesterday on an internal mailing