My application provides a GUI for users to edit xml documents. The resulting documents are used by other automated systems following a shared schema. I figured I could cut down on the amount of code I have to write if I used XSD.EXE to generate classes for me to databind the xml to my winforms controls. The nodes in the document are originally created in code using a default namespace declaration which is explicitly declared on the DocumentElement. To edit the nodes, I "deserialize" the OuterXml property of the target XmlNode into the appropriate class created by XSD.EXE, and the user can modify the properties with databound forms. When they click "Save", my code serializes the classes to xml in order to load them back into the source XmlDocument. That code looks like this:
XmlSerializer serializer = new XmlSerializer(xsdObject.GetType());
StringWriter writer = new StringWriter();
serializer.Serialize(writer, xsdObject);
XmlDocument doc = new XmlDocument();
doc.LoadXml(writer.ToString());
// Retrieve the original XmlNode XmlNode oldNode = this.getDefinitionNode(this.metaData.Definition);oldNode.ParentNode.ReplaceChild(oldNode.OwnerDocument.ImportNode(doc.DocumentElement,
true), oldNode);
It's ugly, but it works. My only problem is that the resulting xml comes with a bunch of extra xmlns attributes:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://superlongschemaurl"
I can delete the first two easily enough with no impact to schema validation, and I understand why I can't delete the last one (it's the namespace identifier that links to my schema). What I don't understand is why the resulting XmlNode that I import above explicitly writes the xmlns declaration to the file, even though the node doesn't have it before serialization, and since the default namespace declaration on the documentElement is in scope for all descendantelements.
When I create the original node in the application, I pass in the correct namespace for schema validation, but it's never explicitly written to the nodes in the document--the declaration appears explicitly only once on the documentElement and nowhere else. Isn't there some way I can associate the namespace with these imported nodes without it explicitly redeclaring it in the output XML I know it doesn't hurt anything, but there are literally thousands of nodes in the source document, all of which will be edited by the user, and these unnecessary declarations actually have a significant impact on the size of the file (which can reach into the megabytes all by itself). Any space savings is significant to performance in a lot of ways, so any input would be really helpful.
(Also, if anyone wants to suggest an easier way than using XSD classes to databind Xml to winforms controls, but that still benefits from schema constraints like XSD classes do, I'd definitely appreciate it.)
Thanks,
Jesse