开发者

Serialise to XML and XSD with Schema Location Results in Invalid XSD.

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 X开发者_运维技巧ML 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.


XML Serialization is meant to serialize your data. If the schemaLocation is part of your data, then you want it in your schema. If it's not in your data, then you shouldn't be serializing it.

Remember that schemaLocation is only a hint for tools that want to refer to the schema. It's not necessary in many cases (Visual Studio, for example).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜