System.Type到XmlSchema内置类型

时间:2013-09-17 14:28:38

标签: c# xml xsd

我正在为XmlSchema编写一些类属性,目前我想在<xs:element type="xs:string">中编写类型。

是否有一些映射类,所以我不必编写自己的switch-case

public class Foo
{
    public string Bar { get; set; }
}

public void WriteProperty()
{
    // get the property that is a string
    PropertyInfo barProperty;
    XmlSchemaElement barElement;

    // I don't want this huge switch case for all basic properties.
    switch(barProperty.PropertyType.FullName)
    {
        case "System.String":
            barElement.SchemaTypeName = new QualifiedName("xs:string");
            break;
        // also for int, and bool, and long....


        default:
            //do other stuff with types that are not default types
            break;
    }
}

1 个答案:

答案 0 :(得分:0)

.NET框架没有映射类或函数来执行您需要的操作。

我建议创建一个映射字典而不是使用大开关:

static Dictionary<string, string> TypeMap = new Dictionary<string, string>() {
  { "System.String", "xs:string" },
  { "System.Int32", "xs:int" },
  . . . 
};

. . . 

  string schemaTypeName;
  if (TypeMap.TryGetValue(barProperty.PropertyType.FullName, out schemaTypeName)) {
    barElement.SchemaTypeName = new QualifiedName("xs:string");
  } else {
    //do other stuff with types that are not default types
  }