2009-11-28 55 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模式。