public XmlSchema GetSchema(int schemaId) { this.ThrowIfNotReady(); try { XmlSchemas schemaCollection = new XmlSchemas(); XmlReflectionImporter importer = new XmlReflectionImporter("http://openiz.org/model"); XmlSchemaExporter exporter = new XmlSchemaExporter(schemaCollection); foreach (var cls in typeof(IImsiServiceContract).GetCustomAttributes <ServiceKnownTypeAttribute>().Select(o => o.Type)) { exporter.ExportTypeMapping(importer.ImportTypeMapping(cls, "http://openiz.org/model")); } if (schemaId > schemaCollection.Count) { WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound; return(null); } else { WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK; WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; return(schemaCollection[schemaId]); } } catch (Exception e) { // WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.InternalServerError; var remoteEndpoint = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, String.Format("{0} - {1}", remoteEndpoint?.Address, e.ToString())); return(null); } }
private void ReflectInternal(ProtocolReflector[] reflectors) { description = new ServiceDescription(); description.TargetNamespace = serviceAttr.Namespace; ServiceDescriptions.Add(description); service = new Service(); string name = serviceAttr.Name; if (name == null || name.Length == 0) { name = serviceType.Name; } service.Name = XmlConvert.EncodeLocalName(name); if (serviceAttr.Description != null && serviceAttr.Description.Length > 0) { service.Documentation = serviceAttr.Description; } description.Services.Add(service); reflectionContext = new Hashtable(); exporter = new XmlSchemaExporter(description.Types.Schemas); importer = SoapReflector.CreateXmlImporter(serviceAttr.Namespace, SoapReflector.ServiceDefaultIsEncoded(serviceType)); WebMethodReflector.IncludeTypes(methods, importer); for (int i = 0; i < reflectors.Length; i++) { reflectors[i].Reflect(); } }
/// <summary> /// Gets the schema for the administrative interface. /// </summary> /// <param name="schemaId">The id of the schema to be retrieved.</param> /// <returns>Returns the administrative interface schema.</returns> public XmlSchema GetSchema(int schemaId) { try { XmlSchemas schemaCollection = new XmlSchemas(); XmlReflectionImporter importer = new XmlReflectionImporter("http://openiz.org/ami"); XmlSchemaExporter exporter = new XmlSchemaExporter(schemaCollection); foreach (var cls in typeof(IAmiContract).GetCustomAttributes <ServiceKnownTypeAttribute>().Select(o => o.Type)) { exporter.ExportTypeMapping(importer.ImportTypeMapping(cls, "http://openiz.org/ami")); } if (schemaId > schemaCollection.Count) { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; return(null); } else { WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK; WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; return(schemaCollection[schemaId]); } } catch (Exception e) { WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.InternalServerError; this.traceSource.TraceEvent(TraceEventType.Error, e.HResult, e.ToString()); return(null); } }
private void ReflectInternal(ProtocolReflector[] reflectors) { this.description = new System.Web.Services.Description.ServiceDescription(); this.description.TargetNamespace = this.serviceAttr.Namespace; this.ServiceDescriptions.Add(this.description); this.service = new System.Web.Services.Description.Service(); string name = this.serviceAttr.Name; if ((name == null) || (name.Length == 0)) { name = this.serviceType.Name; } this.service.Name = XmlConvert.EncodeLocalName(name); if ((this.serviceAttr.Description != null) && (this.serviceAttr.Description.Length > 0)) { this.service.Documentation = this.serviceAttr.Description; } this.description.Services.Add(this.service); this.reflectionContext = new Hashtable(); this.exporter = new XmlSchemaExporter(this.description.Types.Schemas); this.importer = SoapReflector.CreateXmlImporter(this.serviceAttr.Namespace, SoapReflector.ServiceDefaultIsEncoded(this.serviceType)); WebMethodReflector.IncludeTypes(this.methods, this.importer); for (int i = 0; i < reflectors.Length; i++) { reflectors[i].Reflect(); } }
public static void SaveSchema() { String path = System.AppDomain.CurrentDomain.BaseDirectory; String schemaFilename = Path.Combine(path, SchemaFilename); try { Type type = typeof(Config); XmlAttributeOverrides xao = new XmlAttributeOverrides(); AttachXmlAttributes(xao, type); XmlReflectionImporter importer = new XmlReflectionImporter(xao); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); XmlTypeMapping map = importer.ImportTypeMapping(type); exporter.ExportTypeMapping(map); TextWriter tw = new StreamWriter(schemaFilename); schemas[0].Write(tw); tw.Close(); } catch (Exception ex) { } }
public void SaveSchema(string filePath) { XmlSerializer serializer = new XmlSerializer(typeof(ApplicationConfiguration)); using (TextWriter writer = new StreamWriter(filePath)) { serializer.Serialize(writer, this); } XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); //Import the type as an XML mapping XmlTypeMapping mapping = new XmlReflectionImporter().ImportTypeMapping(typeof(ApplicationConfiguration)); //Export the XML mapping into schemas exporter.ExportTypeMapping(mapping); using (TextWriter writer = new StreamWriter(filePath)) { foreach (object schema in schemas) { ((XmlSchema)schema).Write(writer); writer.WriteLine(); } } }
public static XmlSchemaSet Infer(Type type) { XmlSchemaSet schemaSet = new XmlSchemaSet(); XmlReflectionImporter importer = new XmlReflectionImporter(); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); XmlTypeMapping xmlTypeMapping = importer.ImportTypeMapping(type); exporter.ExportTypeMapping(xmlTypeMapping); schemas.Compile(new ValidationEventHandler(delegate(object sender, ValidationEventArgs args) { throw args.Exception; }), false); for (int i = 0; i < schemas.Count; i++) { XmlSchema schema = schemas[i]; schema.Namespaces.Add("xsd", "http://www.w3.org/2001/XMLSchema"); try { schemaSet.Add(schema); } catch (Exception exception2) { if (((exception2 is ThreadAbortException) || (exception2 is StackOverflowException)) || (exception2 is OutOfMemoryException)) { throw; } throw; } } return(schemaSet); }
public static XmlTextReader Get_XSD_Clase(Type Tipo_Searializar, String strNamespace) { XmlReflectionImporter importer = new XmlReflectionImporter(); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); XmlTypeMapping mapping = importer.ImportTypeMapping(Tipo_Searializar, strNamespace); exporter.ExportTypeMapping(mapping); XmlSchema schema; if (!String.IsNullOrEmpty(strNamespace)) { schema = schemas[strNamespace]; } else { schema = schemas[0]; } StringWriter sWriter = new StringWriter(); schema.Write(sWriter); XmlTextReader txtReader = new XmlTextReader(new StringReader(sWriter.ToString())); return(txtReader); }
internal static IEnumerable <XmlSchema> InferXmlSchema(Type type) { var reflectedType = Reflector.GetReflectedType(type); var isDataEntity = reflectedType.IsDataEntity; if (isDataEntity || reflectedType.IsList) { var innerTypes = new HashSet <Type>(); var isArray = !isDataEntity; var elementName = reflectedType.XmlElementName; var schemaXml = new StringBuilder(); schemaXml.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?><xs:schema elementFormDefault=\"qualified\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">"); schemaXml.AppendFormat("<xs:element name=\"{0}\" nillable=\"true\" type=\"{1}\" />", (isArray ? "ArrayOf" : "") + elementName, Reflector.ClrToXmlType(type)); WriteTypeSchema(type, schemaXml, innerTypes); schemaXml.Append("</xs:schema>"); var schema = XmlSchema.Read(new StringReader(schemaXml.ToString()), null); return(schema.Return()); } else { var importer = new XmlReflectionImporter(); var schemas = new XmlSchemas(); var exporter = new XmlSchemaExporter(schemas); var xmlTypeMapping = importer.ImportTypeMapping(type); exporter.ExportTypeMapping(xmlTypeMapping); schemas.Compile(null, false); return(schemas); } }
/// <summary> /// Generate a set of schemas from the given types /// </summary> /// <param name="types">Array of types to generate schemas from</param> /// <returns>An array of schemas</returns> public IList <XmlSchema> GenerateSchemas(Type[] types) { Trace.Assert(types != null); if (types.Length == 0) { return(null); } #region generate the schema from the type XmlReflectionImporter reflectionImporter = new XmlReflectionImporter(); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); foreach (Type type in types) { // we can provide the default namespace as a parameter here XmlTypeMapping map = reflectionImporter.ImportTypeMapping(type); exporter.ExportTypeMapping(map); } #endregion // compile the schemas to make sure they were generated correctly schemas.Compile(null, true); ResolveImportedSchemas(schemas, types[0].Name); // convert the generated schemas to an array of schemas return(XmlSchemasToArray(schemas)); }
public static XmlSchema GetDataSetSchema (XmlTypeMapping mapping, string dataSetName, string dataTableName) { // create schema XmlSchema xsd = new XmlSchema(); xsd.Id = dataSetName; // create dataset-element XmlSchemaElement xsdDataset = new XmlSchemaElement(); xsdDataset.Name = dataSetName; // anonymous complextype XmlSchemaComplexType xsdDatasetType = new XmlSchemaComplexType(); // anonymous sequence XmlSchemaSequence xsdDatasetSequence = new XmlSchemaSequence(); // add sequence to complextype xsdDatasetType.Particle = xsdDatasetSequence; // add complextype to dataset-element xsdDataset.SchemaType = xsdDatasetType; // add mapped type XmlSchemas schemas = new XmlSchemas(); schemas.Add(xsd); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); exporter.ExportTypeMapping(mapping); // get datatable-element and move it to dataset-sequence XmlSchemaObject o = xsd.Items[0]; xsd.Items.RemoveAt(0); xsdDatasetSequence.Items.Add(o); // add dataset-element to xsd xsd.Items.Add(xsdDataset); //schemas.Compile(null, false); // we only need the string return schemas[mapping.Namespace]; }
private static XmlSchema GetXmlSchema<T>() { var schemas = new XmlSchemas(); var xmlImporter = new XmlReflectionImporter(); var xmlExporter = new XmlSchemaExporter(schemas); xmlExporter.ExportTypeMapping(xmlImporter.ImportTypeMapping(typeof(T))); return schemas.Single(); }
public void GenerateSchemas() { Assembly assembly = null; try { assembly = Assembly.LoadFrom((string)assemblies [0]); } catch (Exception ex) { Error(errLoadAssembly, ex.Message); } Type[] types; if (lookupTypes.Count > 0) { types = new Type [lookupTypes.Count]; for (int n = 0; n < lookupTypes.Count; n++) { Type t = assembly.GetType((string)lookupTypes[n]); if (t == null) { Error(typeNotFound, (string)lookupTypes[n]); } types[n] = t; } } else { types = assembly.GetExportedTypes(); } XmlReflectionImporter ri = new XmlReflectionImporter(); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter sx = new XmlSchemaExporter(schemas); foreach (Type type in types) { XmlTypeMapping tm = ri.ImportTypeMapping(type); sx.ExportTypeMapping(tm); } if (schemas.Count == 1) { string fileName = Path.Combine(outputDir, "schema.xsd"); WriteSchema(fileName, schemas [0]); } else { for (int n = 0; n < schemas.Count; n++) { string fileName = Path.Combine(outputDir, "schema" + n + ".xsd"); WriteSchema(fileName, schemas [n]); } } }
public void Reflect(Type type, string url) { XmlSchemaExporter schemaExporter = new XmlSchemaExporter(Schemas); SoapSchemaExporter soapSchemaExporter = new SoapSchemaExporter(Schemas); if (WSConfig.IsSupported(WSProtocol.HttpSoap)) { new Soap11ProtocolReflector().Reflect(this, type, url, schemaExporter, soapSchemaExporter); } #if NET_2_0 if (WSConfig.IsSupported(WSProtocol.HttpSoap12)) { new Soap12ProtocolReflector().Reflect(this, type, url, schemaExporter, soapSchemaExporter); } #endif if (WSConfig.IsSupported(WSProtocol.HttpGet)) { new HttpGetProtocolReflector().Reflect(this, type, url, schemaExporter, soapSchemaExporter); } #if ONLY_1_1 if (WSConfig.IsSupported(WSProtocol.HttpPost) || WSConfig.IsSupported(WSProtocol.HttpPostLocalhost)) #else if (WSConfig.IsSupported(WSProtocol.HttpPost)) #endif { new HttpPostProtocolReflector().Reflect(this, type, url, schemaExporter, soapSchemaExporter); } int i = 0; while (i < types.Schemas.Count) { if (types.Schemas[i].Items.Count == 0) { types.Schemas.RemoveAt(i); } else { i++; } } if (serviceDescriptions.Count == 1) { serviceDescriptions[0].Types = types; } else { foreach (ServiceDescription d in serviceDescriptions) { d.Types = new Types(); for (int n = 0; n < types.Schemas.Count; n++) { ProtocolReflector.AddImport(d, types.Schemas[n].TargetNamespace, GetSchemaUrl(url, n)); } } } }
public static String Get_XSD_String_Clase(Type Tipo_Searializar) { XmlReflectionImporter importer = new XmlReflectionImporter(); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); XmlTypeMapping mapping = importer.ImportTypeMapping(Tipo_Searializar); exporter.ExportTypeMapping(mapping); System.Xml.Schema.XmlSchema schema = schemas[0]; System.IO.StringWriter sWriter = new System.IO.StringWriter(); schema.Write(sWriter); return(sWriter.ToString()); }
static void Main(string[] args) { Sensor se = new Sensor() { Data = 5, otherData = 10, MoreData = 15 }; XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); XmlTypeMapping mapping = new XmlReflectionImporter().ImportTypeMapping(typeof(Sensor)); exporter.ExportTypeMapping(mapping); StringWriter schemaWriter = new StringWriter(); foreach (XmlSchema schema in schemas) { schema.Write(schemaWriter); } XDocument doc = XDocument.Parse(schemaWriter.ToString()); XElement root = doc.Root; XNamespace xs = root.GetNamespaceOfPrefix("xs"); foreach (XElement _class in doc.Descendants(xs + "complexType")) { List <XElement> elements = _class.Descendants(xs + "element").ToList(); if (elements.Count > 0) { XElement complexType = new XElement(xs + "complexType"); _class.Add(complexType); XElement sequence = new XElement(xs + "sequence"); complexType.Add(sequence); foreach (var prop in se.GetType().GetProperties()) { string name = prop.Name; string value = prop.GetValue(se, null).ToString(); XElement element = elements.Where(x => (string)x.Attribute("name") == name).FirstOrDefault(); string strType = (string)element.Attribute("type"); XElement newElement = new XElement(xs + "simpleType", new object[] { new XElement(xs + "restriction", new object[] { new XAttribute("base", strType), new XElement(xs + "enumeration", new XAttribute("value", value)) }) }); sequence.Add(newElement); } } } doc.Save(FILENAME); }
public Program() { XmlReflectionImporter _XmlReflectionImporter = new XmlReflectionImporter(); XmlSchemas _XmlSchemas = new XmlSchemas(); XmlSchemaExporter _XmlSchemaExporter = new XmlSchemaExporter(_XmlSchemas); XmlTypeMapping map = _XmlReflectionImporter.ImportTypeMapping(typeof(Database)); _XmlSchemaExporter.ExportTypeMapping(map); TextWriter _TextWriter = new StreamWriter("asd.xsd"); _XmlSchemas[0].Write(_TextWriter); _TextWriter.Close(); }
static XmlQualifiedName StaticGetSchema(XmlSchemaSet schemaSet) { XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping xmlTypeMapping = importer.ImportTypeMapping(typeof(T)); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); exporter.ExportTypeMapping(xmlTypeMapping); schemas.Compile(new ValidationEventHandler(ValidationCallbackWithErrorCode), true); for (int i = 0; i < schemas.Count; i++) { XmlSchema schema = schemas[i]; schemaSet.Add(schema); } return(new XmlQualifiedName(xmlTypeMapping.TypeName, xmlTypeMapping.Namespace)); }
static void SerializarSchema(Type tipo, string nomeArquivo) { var schemas = new XmlSchemas(); var exporter = new XmlSchemaExporter(schemas); var mapping = new XmlReflectionImporter().ImportTypeMapping(tipo); exporter.ExportTypeMapping(mapping); TextWriter writer = new StreamWriter(nomeArquivo); foreach (XmlSchema schema in schemas) { schema.Write(writer); } writer.Dispose(); }
static XmlSchema GetSchema(Type t) { XmlReflectionImporter xri = new XmlReflectionImporter(); XmlTypeMapping xtm = xri.ImportTypeMapping(t); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter xse = new XmlSchemaExporter(schemas); xse.ExportTypeMapping(xtm); foreach (XmlSchema xs in schemas) { return(xs); } return(null); }
/// <summary> /// Get schema /// </summary> public XmlSchema GetSchema(int schemaId) { this.ThrowIfNotReady(); XmlSchemas schemaCollection = new XmlSchemas(); XmlReflectionImporter importer = new XmlReflectionImporter("http://hl7.org/fhir"); XmlSchemaExporter exporter = new XmlSchemaExporter(schemaCollection); foreach (var cls in typeof(FhirServiceBehavior).Assembly.GetTypes().Where(o => o.GetCustomAttribute <XmlRootAttribute>() != null && !o.IsGenericTypeDefinition)) { exporter.ExportTypeMapping(importer.ImportTypeMapping(cls, "http://hl7.org/fhir")); } return(schemaCollection[schemaId]); }
public static void SchemaDoc(String[] args) { var docParameters = new ParameterParser <SchemaDocParameters>().Parse(args); XmlSchema outputXsd = new XmlSchema(); XmlSchemas outputSchemas = new XmlSchemas(); var schemaExporter = new XmlSchemaExporter(outputSchemas); var reflectionImporter = new XmlReflectionImporter(); Assembly loadedAssembly = Assembly.LoadFile(docParameters.Assembly); // Load the specified types foreach (var t in loadedAssembly.ExportedTypes.Where(o => o.GetCustomAttribute <XmlRootAttribute>() != null)) { var typeMapping = reflectionImporter.ImportTypeMapping(t); schemaExporter.ExportTypeMapping(typeMapping); } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(docParameters.XmlDocFile ?? Path.ChangeExtension(docParameters.Assembly, "xml")); // Schema set objects foreach (XmlSchema itm in outputSchemas) { foreach (object xtype in itm.Items) { if (xtype is XmlSchemaComplexType) { CreateAssemblyDoc(xtype as XmlSchemaComplexType, loadedAssembly.ExportedTypes.FirstOrDefault(o => o.GetCustomAttribute <XmlTypeAttribute>()?.TypeName == (xtype as XmlSchemaComplexType).Name), xmlDoc); } else if (xtype is XmlSchemaSimpleType) { CreateAssemblyDoc(xtype as XmlSchemaSimpleType, loadedAssembly.ExportedTypes.FirstOrDefault(o => o.GetCustomAttribute <XmlTypeAttribute>()?.TypeName == (xtype as XmlSchemaSimpleType).Name), xmlDoc); } } } // Schema writer using (var xwriter = File.Create(docParameters.Output ?? "out.xsd")) foreach (XmlSchema itm in outputSchemas) { itm.Write(xwriter); } }
// If the user schema is generated by WCF, it may contain references to some primitive WCF // types in the following namespaces. We need add those schemas to the schema set by default // so these types can be resolved correctly. // // * http://schemas.microsoft.com/2003/10/Serialization // * http://schemas.microsoft.com/2003/10/Serialization/Arrays // * http://microsoft.com/wsdl/types/ // * http://schemas.datacontract.org/2004/07/System private void AddSchemasForPrimitiveTypes(XmlSchemaSet schemas) { // Add DCS special types XsdDataContractExporter dataContractExporter = new XsdDataContractExporter(schemas); // We want to export Guid, Char, and TimeSpan, however even a single call causes all // schemas to be exported. dataContractExporter.Export(typeof(Guid)); // Export DateTimeOffset, DBNull, array types dataContractExporter.Export(typeof(DateTimeOffset)); dataContractExporter.Export(typeof(DBNull)); dataContractExporter.Export(typeof(bool[])); dataContractExporter.Export(typeof(DateTime[])); dataContractExporter.Export(typeof(decimal[])); dataContractExporter.Export(typeof(double[])); dataContractExporter.Export(typeof(float[])); dataContractExporter.Export(typeof(int[])); dataContractExporter.Export(typeof(long[])); dataContractExporter.Export(typeof(XmlQualifiedName[])); dataContractExporter.Export(typeof(short[])); dataContractExporter.Export(typeof(string[])); dataContractExporter.Export(typeof(uint[])); dataContractExporter.Export(typeof(ulong[])); dataContractExporter.Export(typeof(ushort[])); dataContractExporter.Export(typeof(Char[])); dataContractExporter.Export(typeof(TimeSpan[])); dataContractExporter.Export(typeof(Guid[])); // Arrays of DateTimeOffset and DBNull are not supported // Add XS special types // XmlSchemaExporter takes XmlSchemas so we need that temporarily XmlSchemas xmlSchemas = new XmlSchemas(); XmlReflectionImporter importer = new XmlReflectionImporter(); XmlSchemaExporter xmlExporter = new XmlSchemaExporter(xmlSchemas); xmlExporter.ExportTypeMapping(importer.ImportTypeMapping(typeof(Guid))); xmlExporter.ExportTypeMapping(importer.ImportTypeMapping(typeof(Char))); foreach (XmlSchema schema in xmlSchemas) { schemas.Add(schema); } }
/// <summary> /// Get Schema for a given body /// </summary> /// <param name="body"></param> /// <param name="isXmlSerializerType"></param> /// <returns></returns> private static Message GetXmlSchemaAsMessage(Type body, bool isXmlSerializerType) { System.Collections.IEnumerable schemas; if (isXmlSerializerType) { XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping typeMapping = importer.ImportTypeMapping(body); XmlSchemas s = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(s); exporter.ExportTypeMapping(typeMapping); schemas = s.GetSchemas(null); } else { XsdDataContractExporter exporter = new XsdDataContractExporter(); exporter.Export(body); schemas = exporter.Schemas.Schemas(); } using (MemoryStream stream = new MemoryStream()) { XmlWriterSettings xws = new XmlWriterSettings { Indent = true }; using (XmlWriter writer = XmlWriter.Create(stream, xws)) { if (writer != null) { writer.WriteStartElement("Schemas"); foreach (XmlSchema schema in schemas) { if (schema.TargetNamespace != "http://www.w3.org/2001/XMLSchema") { schema.Write(writer); } } } } stream.Seek(0, SeekOrigin.Begin); using (XmlReader reader = XmlReader.Create(stream)) { return(Message.CreateMessage(MessageVersion.None, null, XElement.Load(reader, LoadOptions.PreserveWhitespace))); } } }
/// <summary> /// Saves the scheme into file. /// </summary> /// <param name="filename">The filename.</param> private static void SaveSchemeIntoFile(string filename, Type schemeForType) { XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); //Import the type as an XML mapping XmlTypeMapping mapping = new XmlReflectionImporter().ImportTypeMapping(schemeForType); //Export the XML mapping into schemas exporter.ExportTypeMapping(mapping); //Print out the schemas using (FileStream fs = new FileStream(Path.Combine(@"C:\XMLFiles", filename), FileMode.Create, FileAccess.Write, FileShare.Read)) { foreach (object schema in schemas) { ((System.Xml.Schema.XmlSchema)schema).Write(fs); } } }
public static string GetSchema <T>() { var xao = new XmlAttributeOverrides(); AttachXmlAttributes(xao, typeof(T)); var importer = new XmlReflectionImporter(xao); var schemas = new XmlSchemas(); var exporter = new XmlSchemaExporter(schemas); var map = importer.ImportTypeMapping(typeof(T)); exporter.ExportTypeMapping(map); using (var ms = new MemoryStream()) { schemas[0].Write(ms); ms.Position = 0; return(new StreamReader(ms).ReadToEnd()); } }
private static XmlReaderSettings CreateXmlReaderSettings <T>() { XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); XmlTypeMapping mapping = new XmlReflectionImporter().ImportTypeMapping(typeof(T)); exporter.ExportTypeMapping(mapping); XmlSchemaSet schemaSet = new XmlSchemaSet(); foreach (XmlSchema schema in schemas) { schemaSet.Add(schema); } XmlReaderSettings settings = new XmlReaderSettings(); settings.Schemas = schemaSet; settings.ValidationType = ValidationType.Schema; settings.ValidationEventHandler += HandleXmlReaderValidation; return(settings); }
public void ExportXmlSerializable_NestedClassMapping() { XmlSchemas schemas = new XmlSchemas(); XmlReflectionMember xmlReflectionMember = new XmlReflectionMember(); XmlSchemaExporter xmlSchemaExporter = new XmlSchemaExporter(schemas); XmlReflectionImporter xmlReflectionImporter = new XmlReflectionImporter(); //Export mapping for DataSet1 class. xmlReflectionMember.MemberType = typeof(DataSet1); XmlMembersMapping xmlMembersMapping = xmlReflectionImporter.ImportMembersMapping("DataSet1Response", "ResponseNamespace", new XmlReflectionMember [] { xmlReflectionMember }, true); xmlSchemaExporter.ExportMembersMapping(xmlMembersMapping); //Export mapping for nested of DataSet1 class. xmlReflectionMember.MemberType = typeof(DataSet1.DataTable1DataTable); xmlMembersMapping = xmlReflectionImporter.ImportMembersMapping("DataTable1DataTableResponse", "ResponseNamespace", new XmlReflectionMember [] { xmlReflectionMember }, true); xmlSchemaExporter.ExportMembersMapping(xmlMembersMapping); }
public static byte[] GetXmlSchemaFromType(Type type) { XmlSchemas sms = new XmlSchemas(); XmlSchemaExporter ex = new XmlSchemaExporter(sms); XmlReflectionImporter im = new XmlReflectionImporter(); XmlTypeMapping map = im.ImportTypeMapping(type); ex.ExportTypeMapping(map); sms.Compile(null, false); MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms); foreach (System.Xml.Schema.XmlSchema sm in sms) { sm.Write(sw); } sw.Close(); ms.Flush(); byte[] data = ms.ToArray(); return(data); }
public string Create(Type t) { string xsd; using (var stream = new MemoryStream()) { using (var writer = new StreamWriter(stream, Encoding.UTF8)) { var schemas = new XmlSchemas(); var exporter = new XmlSchemaExporter(schemas); var mapping = new XmlReflectionImporter().ImportTypeMapping(t); exporter.ExportTypeMapping(mapping); foreach (XmlSchema schema in schemas) { schema.Write(writer); } writer.Flush(); xsd = Encoding.UTF8.GetString(stream.ToArray()); } } xsd = ManipulateXsdForScriptContent(xsd); return(xsd); }
static int Main () { XmlReflectionImporter ri = new XmlReflectionImporter ("NSPrimitive"); XmlSchemas schemas = new XmlSchemas (); XmlSchemaExporter sx = new XmlSchemaExporter (schemas); XmlTypeMapping tm = ri.ImportTypeMapping (typeof (int)); sx.ExportTypeMapping (tm); StringWriter sw = new StringWriter (); schemas[0].Write (sw); int exitCode = 0; exitCode += Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + "<xs:schema xmlns:tns=\"NSPrimitive\" elementFormDefault=\"qualified\" targetNamespace=\"NSPrimitive\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + " <xs:element name=\"int\" type=\"xs:int\" />{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#1"); ri = new XmlReflectionImporter ("NSString"); schemas = new XmlSchemas (); sx = new XmlSchemaExporter (schemas); tm = ri.ImportTypeMapping (typeof (string)); sx.ExportTypeMapping (tm); sw = new StringWriter (); schemas[0].Write (sw); exitCode += Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + "<xs:schema xmlns:tns=\"NSString\" elementFormDefault=\"qualified\" targetNamespace=\"NSString\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + " <xs:element name=\"string\" nillable=\"true\" type=\"xs:string\" />{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#2"); ri = new XmlReflectionImporter ("NSQName"); schemas = new XmlSchemas (); sx = new XmlSchemaExporter (schemas); tm = ri.ImportTypeMapping (typeof (XmlQualifiedName)); sx.ExportTypeMapping (tm); sw = new StringWriter (); schemas[0].Write (sw); exitCode += Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + "<xs:schema xmlns:tns=\"NSQName\" elementFormDefault=\"qualified\" targetNamespace=\"NSQName\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + #if NET_2_0 " <xs:element name=\"QName\" nillable=\"true\" type=\"xs:QName\" />{0}" + #else " <xs:element name=\"QName\" type=\"xs:QName\" />{0}" + #endif "</xs:schema>", Environment.NewLine), sw.ToString (), "#3"); ri = new XmlReflectionImporter ("NSDateTime"); schemas = new XmlSchemas (); sx = new XmlSchemaExporter (schemas); tm = ri.ImportTypeMapping (typeof (DateTime)); sx.ExportTypeMapping (tm); sw = new StringWriter (); schemas[0].Write (sw); exitCode += Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + "<xs:schema xmlns:tns=\"NSDateTime\" elementFormDefault=\"qualified\" targetNamespace=\"NSDateTime\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + " <xs:element name=\"dateTime\" type=\"xs:dateTime\" />{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#4"); ri = new XmlReflectionImporter ("NSByteArray"); schemas = new XmlSchemas (); sx = new XmlSchemaExporter (schemas); tm = ri.ImportTypeMapping (typeof (byte[])); sx.ExportTypeMapping (tm); sw = new StringWriter (); schemas[0].Write (sw); exitCode += Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + "<xs:schema xmlns:tns=\"NSByteArray\" elementFormDefault=\"qualified\" targetNamespace=\"NSByteArray\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + " <xs:element name=\"base64Binary\" nillable=\"true\" type=\"xs:base64Binary\" />{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#5"); ri = new XmlReflectionImporter ("NSInt32Array"); schemas = new XmlSchemas (); sx = new XmlSchemaExporter (schemas); tm = ri.ImportTypeMapping (typeof (int[])); sx.ExportTypeMapping (tm); sw = new StringWriter (); schemas[0].Write (sw); exitCode += Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + "<xs:schema xmlns:tns=\"NSInt32Array\" elementFormDefault=\"qualified\" targetNamespace=\"NSInt32Array\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + " <xs:element name=\"ArrayOfInt\" nillable=\"true\" type=\"tns:ArrayOfInt\" />{0}" + " <xs:complexType name=\"ArrayOfInt\">{0}" + " <xs:sequence>{0}" + " <xs:element minOccurs=\"0\" maxOccurs=\"unbounded\" name=\"int\" type=\"xs:int\" />{0}" + " </xs:sequence>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#6"); ri = new XmlReflectionImporter ("NSSimpleClassArray"); schemas = new XmlSchemas (); sx = new XmlSchemaExporter (schemas); tm = ri.ImportTypeMapping (typeof (SimpleClass[])); sx.ExportTypeMapping (tm); sw = new StringWriter (); schemas[0].Write (sw); exitCode += Assert.AreEqual (string.Format (CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + "<xs:schema xmlns:tns=\"NSSimpleClassArray\" elementFormDefault=\"qualified\" targetNamespace=\"NSSimpleClassArray\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + " <xs:element name=\"ArrayOfSimpleClass\" nillable=\"true\" type=\"tns:ArrayOfSimpleClass\" />{0}" + " <xs:complexType name=\"ArrayOfSimpleClass\">{0}" + " <xs:sequence>{0}" + " <xs:element minOccurs=\"0\" maxOccurs=\"unbounded\" name=\"SimpleClass\" nillable=\"true\" type=\"tns:SimpleClass\" />{0}" + " </xs:sequence>{0}" + " </xs:complexType>{0}" + " <xs:complexType name=\"SimpleClass\" />{0}" + "</xs:schema>", Environment.NewLine), sw.ToString (), "#7"); return exitCode; }