I am using the .Net XmlSerializer
to serialize an object to an XML document, in a C# Windows Forms application.
The root element should end up looking like:
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="file:///C:/data//MySchema.xsd">
<!-- ... -->
</root>
In a partial class (to join the partial class created by xsd.exe
), I have added the following property to add the xsi:noNamespaceSchemaLocation
attribute.
[XmlAttribute("noNamespaceSchemaLocation", Namespace = XmlSchema.InstanceNamespace)]
public string xsiNoNamespaceSchemaLocation = @"file:///C://data//MySchema.xsd";
And to remove all the other namespaces, but keep the xsi
one I have used:
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
And then passed ns
to the XmlSerializer.Serialize()
method.
This works so far, but I'm not sure if this is correct. It feels like I'm removing what is there by default, only to try add a piece of it back again... seems like a code smell.
Maybe is there a better way that only removes the xsd
but leaving the default xsi
, so I don't need to add it back in again?
Note: There is an unanswered question on this already from some time back here, the only suggested answer does not suit as it removes both xsd
and xsi
attributes.