views:

2463

answers:

3

The following questions are about XML serialization/deserialization and schema validation for a .net library of types which are to be used for data exchange.


First question, if I have a custom xml namespace say "http://mydomain/mynamespace" do I have to add a

[XmlRoot(Namespace = "http://mydomain/mynamespace")]

to every class in my library. Or is there a way to define this namespace as default for the whole assembly?


Second question, is there a reason behind the always added namespaces

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"

even if there is no actual reference to any of the namespaces? I just feel they add noise to the resulting xml. Is there a way to remove them an only have the custom namespace in the resulting xml?


Third question, are there tools to support the generation of schema definitions (e.g. for all public [Serializable] classes of an assembly) and the validation of xml against specific schemas available?

If there are, would you recommend XML Schema from W3C or RELAX NG?

+1  A: 

1) XmlRoot can only be set at the class/struct/interface level (or on return values). So you can't use it on the assembly level. What you're looking for is the XmlnsDefinitionAttribute, but I believe that only is used by the XamlWriter.

2) If you're worried about clutter you should avoid xml. Well formed xml is full of clutter. I believe there are ways to interract with the xml produced by the serializer, but not directly with the XmlSerializer. You have much more control over the XML produced with the XmlWriter class. Check here for how you can use the XmlWriter to handle namespaces.

3) XSD.exe can be used to generate schemas for POCOs, I believe (I've always written them by hand; I may be using this soon to write up LOTS, tho!).

Will
+3  A: 

Just to add - the "xsi" etc is there to support things like xsi:nil on values later on - a well-known pattern for nullable values. It has to write the stream "forwards only", and it doesn't know (when it writes the first bit) whether it will need nil or not, so it assumes that writing it unnecessarily once is better than having to use the full namespace potentially lots of times.

Marc Gravell
A: 

Tools, - xsd.exe, with a command line like

xsd /c /n:myNamespace.Schema.v2_0  myschema_v2_0.xsd

I put the schema in a separate project.

liqudXML which is useful if there are several schemas, or you want full support of the schema features (DateTimes with offsets, positive/Negative decimals,), and cross platform generation.

david valentine