2009-11-28 23 views
0

我想实现IXmlSerializable。 我的类实现可串行化并写入一个字符串。我希望能够使用XsdDataContractExporter(标准的)导出对象图模式。IXmlSerializable与有效的XmlSchema(XMLSchema:架构'元素未声明..)

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

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

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

我需要能够生成和导出架构。

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

我得到以下错误:

The http://www.w3.org/2001/XMLSchema:schema element is not declared..
当我尝试导出模式。

+0

'导出模式':你的意思是当你将它添加到一个XML文件实现? – 2009-11-28 15:21:25

回答

0

尝试在单独的文件中编写XSD模式(在运行时编写它更容易)。 确保它是有效的。 将xsd模式作为资源放入您的程序集中。 然后,在你的getSchema方法只反序列化:

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

还注意到自己的方法的getSchema将在运行时调用的任何(德)序列化。 因此,每一次它不是一个好主意,都要进行desirializing模式。