2011-07-29 41 views
0

我正在使用.NET 3.5将一个类序列化到Xml并创建一个XSD模式。生成的XML使用模式位置属性引用XSD。序列化为XML和XSD,其架构位置结果在无效XSD中。

我的解决方案是基于这些问题的答案: XmlSerialization and xsi:SchemaLocation (xsd.exe)XML Serialization and Schema without xsd.exe

我的属性添加到我的类引用XSD:

[XmlAttribute("schemaLocation", Namespace = XmlSchema.InstanceNamespace)] 
public string XsiSchemaLocation = "MyNameSpace " + "MyNameSpace.xsd"; 

的问题是,现场XsiSchemaLocation在结束了我的XSD文件:

<xs:attribute xmlns:q1="http://www.w3.org/2001/XMLSchema-instance" ref="q1:schemaLocation" /> 

当我尝试编辑序列化的XML文件自动完成在Visual Studio不会因为上述属性的工作,给下面的错误:

The ' http://www.w3.org/2001/XMLSchema-instance:schemaLocation ' attribute is not declared.

我目前的解决方案,请从XSD架构位置属性是低于黑客:

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); 
    } 

有没有比强制删除属性更好的方法。像[XmlSchemaIgnore]属性就好像是完美的。

回答

0

XML序列化旨在序列化您的数据。如果schemaLocation是您数据的一部分,那么您希望在您的模式中使用它。如果它不在你的数据中,那么你不应该序列化它。

请记住,schemaLocation仅仅是希望引用该模式的工具的提示。在许多情况下(例如Visual Studio)并不是必需的。

+0

当我连载我的数据schemaLocation正确地出现在xsi:schemaLocation =“MyNameSpace MyNameSpace.xsd”的XML文件中。 问题是,schemaLocation不应被视为我的XSD架构的一部分,它应该是导入架构的一部分(通过XmlSchema.InstanceNamespace)。 我想intellisense在Visual Studio中工作,如果有人编辑我的序列化数据,没有schemaLocation intellisense不起作用,所以这是必要的在我的情况。 – row1

+0

你错了。如果模式文件位于同一项目中,或者“手动”设置要使用的模式,则Intellisense将起作用。再一次,你不能两面都有。 –

+0

这些文件不存在于项目中,因此如果没有模式位置,Intellisense不起作用。我希望配置工程师在Visual Studio中的远程服务器上打开此文件并对其进行编辑,如果他们必须手动选择模式,则很麻烦。我链接的答案表明,我对模式位置的使用对于序列化来说是正确的,所以不幸的是它似乎不适用于XSD生成。 – row1