Xml Serialization and Schemas in .net (C #)

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

First question, if I have my own xml namespace say " http: // mydomain / mynamespace " I need to add

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


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

Second question, is there any reason for the 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 namespace? I just feel like they are adding noise to the resulting xml. Is there a way to remove them, they only have their own namespace in the resulting xml?

Third question: are there tools to support generation of schema definitions (for example, for all public [Serializable] assembly classes) and xml validation for certain available schemas?

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


source to share

3 answers

Just add - "xsi" etc. to support things like xsi: nil over values ​​later - a well-known pattern for null values. He only has to write the stream "forward" and he doesn't know (when he writes the first bit) if it will be null or not, so he assumes that writing it unnecessarily once is better than using the full namespace potentially many times.



1) XmlRoot can only be set at the class / structure / interface level (or on return values). Therefore, you cannot use it at the assembly level. What you are looking for is the XmlnsDefinitionAttribute , but I believe this is only used by the XamlWriter.

2) If you are worried about clutter, you should avoid xml. Well-formed xml is full of clutter. I believe there are ways to pull in the xml generated by the serializer, but not directly with the XmlSerializer. You have a lot more control over the XML generated by the XmlWriter class . Check here how you can use the XmlWriter to handle namespaces.

3) XSD.exe can be used to create schemas for POCOs I believe (I always wrote them by hand; may use that soon to write LOTS, tho!).



Tools, - xsd.exe, with command line like

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


I am putting the circuit in a separate project.

liquiddXML , which is useful if you have multiple schemas, or you want to fully support schema features (DateTimes with offsets, positive / negative decimals) as well as cross platform creation.



All Articles