2010-07-09 43 views
1

CLR类型和xsd类型代码之间是否存在标准(框架)映射? 我需要将字符串,int,小数等转换为等效的XmlSchemaSimpleType。从System.Type到xs的类型映射:类型

我可以构造必要的简单类型并使用case语句来自己完成映射。我希望他们可能是一个标准框架类,可以从各种CLR类型构造XmlSchemaSimpleType,或者甚至可以从CLR类型映射到XmlTypeCode。

System.String - > XmlTypeCode.String(例如)

感谢

UPDATE(07-07-2010) 谢谢,我看过它需要一个小调整的链接 - 为别人,这里是可以粘贴到linqpad的最终代码。

public class XmlValueWrapper 
{ 
    public object Value { get; set; } 
} 

public static class XsdConvert 
{ 
    private static XmlSerializer serializer = new XmlSerializer(typeof(XmlValueWrapper)); 


    public static object ConvertFrom(string value, string xsdType) 
    { 
     XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; 
     XNamespace xsd = "http://www.w3.org/2001/XMLSchema"; 
     XDocument doc = new XDocument(
      new XElement("XmlValueWrapper", 
       new XAttribute(XNamespace.Xmlns + "xsi", xsi), 
       new XAttribute(XNamespace.Xmlns + "xs", xsd), 
        new XElement("Value", 
         new XAttribute(xsi + "type", xsdType), 
         new XText(value)) 
      ) 
     ); 
     doc.Dump("try"); 

     using (var reader = doc.CreateReader()) { 
      XmlValueWrapper wrapper = (XmlValueWrapper) serializer.Deserialize(reader); 
      wrapper.Dump("ITEM"); 
      return wrapper.Value; 
     } 
    } 

} 
    public static void Main() 
    { 
     object o = XsdConvert.ConvertFrom("2010-01-02", "xs:date"); 
     o.GetType().Dump("object"); 
     /* 
     Debug.Assert(Equals(42, XsdConverta.ConvertFrom("42", "xsd:int"))); 
     Debug.Assert(Equals(42.0, XsdConverta.ConvertFrom("42", "xsd:double"))); 
     Debug.Assert(Equals(42m, XsdConverta.ConvertFrom("42", "xsd:decimal"))); 
     Debug.Assert(Equals("42", XsdConverta.ConvertFrom("42", "xsd:string"))); 
     Debug.Assert(Equals(true, XsdConverta.ConvertFrom("true", "xsd:boolean"))); 
     Debug.Assert(Equals(new DateTime(2009, 4, 17), XsdConverta.ConvertFrom("2009-04-17", "xsd:date")));*/ 
    } 

回答