【发布时间】:2011-10-15 15:30:21
【问题描述】:
我正在使用 .NET 3.5 将类序列化为 Xml 并创建 XSD 架构。生成的 XML 使用架构位置属性引用 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" />
当我尝试在 Visual Studio 中编辑我的序列化 XML 文件时,由于上述属性,自动完成功能不起作用并给出以下错误:
“http://www.w3.org/2001/XMLSchema-instance:schemaLocation”属性未声明。
我目前从 XSD 中删除架构位置属性的解决方案是以下 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);
}
有没有比强制删除属性更好的方法。像 [XmlSchemaIgnore] 属性这样的东西会很完美。
【问题讨论】:
标签: c# xml xml-serialization xsd