views:

162

answers:

3

I have a load of classes and I need to generate an XML schema for these classes.

The easiest way I can think to do this is to create the classes, serialize as XML and then run XSD on this XML.

However, if I don't set the properties of a class, no XML node is created and therefore the XSD doesn't pick it up.

Is there a way for me to tell the XML serializer to serialize ALL properties of a class, rather than just the ones that have values set?

Hopeful, more than expecting! Duncan

+2  A: 

Sure. Implement IXmlSerializable and you have complete control.

Also, I am sure you already know there are a couple different ways to parse/validate Xml… and since you are on the Microsoft platform… these tools (available on MSDN) come in handy (auto generate C# code) if you decide to serialize/deserialize to/from a schema: xsd.exe and xsdObjectGen.exe (more options).

Kris Krause
Thanks, I forgot about this. I was also wondering if there was a magic attribute I could attach to my class which would do the above without me needing to implement this interface?
Duncan
+2  A: 

Use metadata attribute

[XmlElement(IsNullable=true)]

It will, however, add extra attribute xsi:nil="true" to the serialized output, if the field is null.

Skrim
+2  A: 

XSD.EXE can generate schemas from an assembly. Just specify the /type switch.

John Saunders
Thanks, as a reminder to everyone you need to give the fully qualified namespace, like so:xsd Assembly.dll /type:namespace.* /outputdir:C:\temp
Duncan