【发布时间】:2012-04-11 12:42:16
【问题描述】:
我需要在我的 xsd 架构中使用在不同程序集中定义的复杂类型。我的两个 .xsd 架构都被定义为嵌入式资源,我试图链接我必须在程序集中导入的工作表,谁需要它却没有结果。
基本上,当我需要验证我的 xml 页面之一时,我会调用此函数,但它无法级联添加 Operations 中类型的 xml 模式集。
public static XmlSchema GetDocumentSchema(this Document doc)
{
var actualType = doc.GetType();
var stream = actualType.Assembly.GetManifestResourceStream(actualType.FullName);
if (stream == null)
{
throw new FileNotFoundException("Unable to load the embedded file [" + actualType.FullName + "]");
}
var documentSchema = XmlSchema.Read(stream, null);
foreach (XmlSchemaExternal xmlInclude in documentSchema.Includes)
{
var includeStream = xmlInclude.SchemaLocation != "Operations.xsd"
? actualType.Assembly.GetManifestResourceStream(xmlInclude.Id)
: typeof (Operations).Assembly.GetManifestResourceStream(xmlInclude.Id);
if (includeStream == null)
{
throw new FileNotFoundException("Unable to load the embedded include file [" + xmlInclude.Id + "]");
}
xmlInclude.Schema = XmlSchema.Read(includeStream, null);
}
return documentSchema;
}
这是主架构:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="ExampleSheet"
attributeFormDefault="unqualified"
elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:include id="Operations" schemaLocation="Operations.xsd"/>
<xs:element name="ExampleSheet">
<xs:complexType>
<xs:sequence>
<xs:element name="Operations" type="Operations"/>
</xs:sequence>
<xs:attribute name="version" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>
这是操作的架构:
<xs:schema id="Operations"
elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
<xs:element name="Operations" type="Operations"/>
<xs:complexType name="Operations">
<xs:choice minOccurs="1" maxOccurs="unbounded">
<xs:element name="Insert" type="Insert"/>
<xs:element name="InsertUpdate" type="InsertUpdate"/>
<xs:element name="Update" type="Update"/>
<xs:element name="Delete" type="Delete"/>
</xs:choice>
<xs:attribute name="version" type="xs:string" use="required"/>
<xs:attribute name="store" type="xs:string" use="required"/>
<xs:attribute name="chain" type="xs:string" use="optional"/>
</xs:complexType>
</xs:schema>
例如,如果我有一个带有插入的 ExampleSheet,它就无法识别它。 Operations 和 Insert 是实现 IXmlSerializable 的类,第一个类使用自定义 XmlSchemaProvider 检索内部类型的架构集。
我做错了吗? 如何帮助我的 ExampleSheet 接受操作成员? ExampleSheet 是否应该实现 IXmlSerializable 以便我可以根据需要构建读取器和写入器,并且架构仍然有用吗?
【问题讨论】:
-
很难跟上你:) - 简单地说,你想从另一个模式中引用一个模式,是吗?
-
@NSGaga 是的,来自不同的程序集。抱歉我的解释不好:)
-
@NSGaga 不是真的,我已经尝试过 xs:import 和 xs:include ,实际上它们在同一个命名空间中。我省略了它们以使模式更易于阅读。
-
不知道这是否与
XmlSerialization兼容,但您是否查看了XmlSchemaSet类而不是XmlSchema。然后,您可以将ExampleSheet和Operations模式添加到集合中,并且您应该可以访问每个模式中的所有元素。
标签: c# xml-serialization xsd