code_junkie

XML Serialization and Schema without xsd.exe

Nov 12th, 2011
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. XmlReflectionImporter importer = new XmlReflectionImporter();
  2. XmlSchemas schemas = new XmlSchemas();
  3. XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);
  4. Type type = toSerialize.GetType();
  5. XmlTypeMapping map = importer.ImportTypeMapping(type);
  6. exporter.ExportTypeMapping(map);
  7.  
  8. TextWriter tw = new StreamWriter(fileName + ".xsd");
  9. schemas[0].Write(tw);
  10. tw.Close();
  11.  
  12. public class Test
  13. {
  14. [XmlAttribute()]
  15. public string Attribute { get; set; }
  16. public string Description { get; set; }
  17.  
  18. [XmlArray(ElementName = "Customers")]
  19. [XmlArrayItem(ElementName = "Customer")]
  20. public List<CustomerClass> blah { get; set; }
  21.  
  22. }
  23.  
  24. public static void AttachXmlAttributes(XmlAttributeOverrides xao, Type t)
  25. {
  26. List<Type> types = new List<Type>();
  27. AttachXmlAttributes(xao, types, t);
  28. }
  29.  
  30. public static void AttachXmlAttributes(XmlAttributeOverrides xao, List<Type> all, Type t)
  31. {
  32. if(all.Contains(t))
  33. return;
  34. else
  35. all.Add(t);
  36.  
  37. XmlAttributes list1 = GetAttributeList(t.GetCustomAttributes(false));
  38. xao.Add(t, list1);
  39.  
  40. foreach (var prop in t.GetProperties())
  41. {
  42. XmlAttributes list2 = GetAttributeList(prop.GetCustomAttributes(false));
  43. xao.Add(t, prop.Name, list2);
  44. AttachXmlAttributes(xao, all, prop.PropertyType);
  45. }
  46. }
  47.  
  48. private static XmlAttributes GetAttributeList(object[] attributes)
  49. {
  50. XmlAttributes list = new XmlAttributes();
  51. foreach (var attribute in attributes)
  52. {
  53. Type type = attribute.GetType();
  54. if (type.Name == "XmlAttributeAttribute") list.XmlAttribute = (XmlAttributeAttribute)attribute;
  55. else if (type.Name == "XmlArrayAttribute") list.XmlArray = (XmlArrayAttribute)attribute;
  56. else if (type.Name == "XmlArrayItemAttribute") list.XmlArrayItems.Add((XmlArrayItemAttribute)attribute);
  57.  
  58. }
  59. return list;
  60. }
  61. public static string GetSchema<T>()
  62. {
  63. XmlAttributeOverrides xao = new XmlAttributeOverrides();
  64. AttachXmlAttributes(xao, typeof(T));
  65.  
  66. XmlReflectionImporter importer = new XmlReflectionImporter(xao);
  67. XmlSchemas schemas = new XmlSchemas();
  68. XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);
  69. XmlTypeMapping map = importer.ImportTypeMapping(typeof(T));
  70. exporter.ExportTypeMapping(map);
  71.  
  72. using (MemoryStream ms = new MemoryStream())
  73. {
  74. schemas[0].Write(ms);
  75. ms.Position = 0;
  76. return new StreamReader(ms).ReadToEnd();
  77. }
  78. }
Add Comment
Please, Sign In to add comment