0

我正在尝试实现 IXmlSerializable。我的类实现了可序列化并编写了一个字符串。我希望能够使用 XsdDataContractExporter(标准模式)导出对象图模式。

该类序列化为一个简单的 xml。

<Urn ns='http://palantir.co.za/urn'>somestring</Urn>

我的GetSchema实现,对应XmlSchemaProvider属性如下。

我需要能够生成和导出模式。

    public static XmlQualifiedName GetSchema(XmlSchemaSet xs)
    {
        string ns = "http://palantir.co.za/urn";
        if (xs.Schemas("http://palantir.co.za/urn").Count != 0)
            return new XmlQualifiedName("Urn", ns); // tried many.

        XmlSchema schema = new XmlSchema();
        schema.Namespaces.Add("xs", XmlSchema.Namespace);
        schema.Namespaces.Add("Urn", ns); // tried many prefixes.
        schema.ElementFormDefault = XmlSchemaForm.Qualified;
        schema.Items.Add(
            new XmlSchemaElement() {                    
                Name = "Urn",
                SchemaTypeName = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).QualifiedName
            });

        schema.TargetNamespace = ns;
        xs.Add(schema);
        //xs.Compile();
        return new XmlQualifiedName("Urn", schema.TargetNamespace);
    }

我收到以下错误:

未声明http://www.w3.org/2001/XMLSchema:schema元素。   
当我尝试导出架构时。

4

1 回答 1

0

尝试在单独的文件中编写 XSD 架构(在运行时编写要容易得多)。确保它是正确的。将 xsd 模式作为资源放入您的程序集中。然后,在您的 GetSchema 方法中反序列化它:

using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
    return XmlSchema.Read(stream, null);
}

另请注意,您的方法 GetSchema 将在任何(反)序列化的运行时调用。因此,每次都对模式进行反序列化并不是一个好主意。

于 2009-12-08T15:56:08.860 回答