开发者

IXmlSerializable with valid XmlSchema (XMLSchema:schema' element is not declared..)

I am trying to implement IXmlSerializable. My class implements serializable and writes a single string. I wish to be able to export an object graph schema using XsdDataContractExporter (the standard one).

The class serializes to a simple xml.

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

My implementation of GetSchema, which corresponds to the XmlSchemaProvider attribute is as follows.

I need to be able to generate and export the schema.

    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;
 开发者_StackOverflow中文版       xs.Add(schema);
        //xs.Compile();
        return new XmlQualifiedName("Urn", schema.TargetNamespace);
    }

I get the following error:

The http://www.w3.org/2001/XMLSchema:schema element is not declared..   
when I try to export the schema.


Try compose XSD schema in separate file (it much easier that composing in runtime). Make sure it's correnct. Place xsd schema into your assembly as a resource. Then, in your GetSchema method just deserialize it :

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

Also notice that your method GetSchema will be called in runtime on any (de)serialization. So desirializing schema each time itsn't good idea.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜