I am using .NET 3.5 to serialise a class to Xml and to create an XSD schema. The generated XML references the XSD using the schema location attribute.
My solution is based on these answers: XmlSerialization and xsi:SchemaLocation (xsd.exe) and XML Serialization and Schema without xsd.exe
I add an attribute to my class to reference the XSD:
[XmlAttribute("schemaLocation", Namespace = XmlSchema.InstanceNamespace)]
public string XsiSchemaLocation = "MyNameSpace " + "MyNameSpace.xsd";
The problem is that the field XsiSchemaLocation ends up in my XSD file:
<xs:attribute xmlns:q1="http://www.w3.org/2001/XMLSchema-instance" ref="q1:schemaLocation" />
When I try to edit my serialised XML file auto-complete in Visual Studio doesn't work because of the above attribute and gives the below error:
The 'http://www.w3.org/2001/XMLSchema-instance:schemaLocation' attribute is not declared.
My current solution to remove the schema location attribute from the XSD is the below hack:
XmlReflectionImporter importer = new XmlReflectionImporter();
XmlSchemas schemas = new XmlSchemas();
XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);
XmlTypeMapping map = importer.ImportTypeMapping(m_SerializedType);
exporter.ExportTypeMapping(map);
using (var tw = new StreamWriter(m_XsdPath))
{
//Hack to remove the schema location from the XSD.
((System.Xml.Schema.XmlSchemaComplexType)(schemas[0].Items[1])).Attributes.Clear();
schemas[0].Write(tw);
}
Is there a better way than forcibly removing the attribute. Something like an [XmlSchemaIgnore] attribute would be perfect.