Get an XML datatype from a .NET type?
I'm wondering if there is a library - in .NET or otherwise - that will convert .NET types (eg. Integer
, String
, etc.) into XML datatypes (eg. int
, string
).开发者_Python百科 Note that I'm looking to convert types, not the content of variables. For example:
var xmlType = Convert.ToXmlType(typeof(bool));
Assert.That(xmlType.ToString(), Is.EqualTo("boolean"));
I don't mind making a lookup table since I'm not dealing with too many types, but I thought it would be nice to reuse such a thing if it's already out there.
You can use the following code to create the mappings, however it is not a one-to-one mapping. Reducing this to one-to-one will have to be an implementation detail on your end:
var mapping = (from XmlTypeCode cc in Enum.GetValues(typeof(XmlTypeCode))
let xt = XmlSchemaType.GetBuiltInSimpleType(cc)
where xt != null
group cc by xt.Datatype.ValueType into gg
select new { Type = gg.Key, XmlTypeCodes = gg.ToArray() })
.ToDictionary(m => m.Type, m => m.XmlTypeCodes);
Sample output:
System.Boolean => Boolean
System.Byte => UnsignedByte
System.Byte[] => HexBinary,Base64Binary
System.DateTime => DateTime,Time,Date,GYearMonth,GYear,GMonthDay,GDay,GMonth
System.Decimal => Decimal,Integer,NonPositiveInteger,NegativeInteger,NonNegative
Integer,PositiveInteger
...
A decent approach to solving the one-to-one problem would be to take the first entry in the code table which works for every type but String
. This also may not work for newer BCL types, but likely should going forward. It would be a breaking change for MS to rearrange the XmlTypeCode
enumeration, but that's not to say this is fool proof:
// same as above except the ToDictionary
.ToDictionary(
m => m.Type,
m => m.Type != typeof(string) ? m.XmlTypeCodes.First() : XmlTypeCode.String);
I found a second aproach using the framework itselfe.
XmlTypeMapping getQualifiedNameForSystemType(Type systemType_in)
{
SoapReflectionImporter sri = new SoapReflectionImporter();
return sri.ImportTypeMapping(systemType_in);
}
精彩评论