Finding CLR Types from Schema


How can I found out what CLR type a particular XML schema definition will map to when using data contracts?

Ask the type system what type it thinks the schema will map to.

static string ClrTypeForXmlType(XmlQualifiedName xmlType)
{
return new XsdDataContractImporter().GetCodeTypeReference(xmlType).BaseType;
}

static void Main(string[] args)
{
Console.WriteLine(ClrTypeForXmlType(new XmlQualifiedName("duration", "http://www.w3.org/2001/XMLSchema")));
Console.WriteLine(ClrTypeForXmlType(new XmlQualifiedName("token", "http://www.w3.org/2001/XMLSchema")));
Console.WriteLine(ClrTypeForXmlType(new XmlQualifiedName("dateTime", "http://www.w3.org/2001/XMLSchema")));
Console.WriteLine(ClrTypeForXmlType(new XmlQualifiedName("anyURI", "http://www.w3.org/2001/XMLSchema")));
Console.WriteLine(ClrTypeForXmlType(new XmlQualifiedName("decimal", "http://www.w3.org/2001/XMLSchema")));
Console.WriteLine(ClrTypeForXmlType(new XmlQualifiedName("positiveInteger", "http://www.w3.org/2001/XMLSchema")));
Console.WriteLine(ClrTypeForXmlType(new XmlQualifiedName("QName", "http://www.w3.org/2001/XMLSchema")));
}

This produces the following list of types.

System.TimeSpan

System.String

System.DateTime

System.Uri

System.Decimal

System.Int64

System.Xml.XmlQualifiedName

Comments (0)

Skip to main content