/// <summary> /// Load an Schema From A File Location /// </summary> /// <param name="SchemaFileLocation">Schema File Location</param> /// <param name="TargetNamespace">Default Namespace - Could be a blank string</param> /// <returns>XmlSchemaSet Object</returns> public static XmlSchemaSet LoadSchemaSetFromFileLocation(string SchemaFileLocation, string TargetNamespace) { //Make sure the file is there if (!File.Exists(SchemaFileLocation)) { throw new FileNotFoundException("Can't Find Schema File In: " + SchemaFileLocation); } //Make sure its a .xsd file if (!string.Equals(new FileInfo(SchemaFileLocation).Extension, ".xsd", StringComparison.OrdinalIgnoreCase)) { throw new InvalidDataException("Schema File Must Be Of Extension .xsd"); } //*************Done with validation************* //Schema To Load var SchemaSet = new XmlSchemaSet(); //Add the file xsd file to the path SchemaSet.Add(TargetNamespace, SchemaFileLocation); //Compile The Schema SchemaSet.Compile(); //Return the XMLSchemaSet return SchemaSet; }
public void v2() { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); XmlSchema schema = new XmlSchema(); sc.Add(null, TestData._XsdNoNs); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Compile(); CError.Compare(sc.IsCompiled, true, "IsCompiled"); CError.Compare(sc.Count, 1, "Count"); try { schema = sc.Add(null, Path.Combine(TestData._Root, "include_v2.xsd")); } catch (XmlSchemaException) { // no schema should be addded to the set. CError.Compare(sc.Count, 1, "Count"); CError.Compare(sc.IsCompiled, true, "IsCompiled"); return; } Assert.True(false); }
public void Verify(string resourceName) { // build a standard configurationsection with properties (using the mock object) var enterpriseConfig = new EnterpriseConfig(); XmlHelper.UseAll = true; var configType = enterpriseConfig.GetType(); var generator = new XsdGenerator(configType); XmlSchema schema = generator.GenerateXsd(configType.FullName); var schemaXml = SchemaToString(schema); var schemas = new XmlSchemaSet(); schemas.Add("http://JFDI.Utils.XSDExtractor.UnitTests.ConfigurationClasses.EnterpriseConfig", XmlReader.Create(new StringReader(schemaXml))); schemas.CompilationSettings.EnableUpaCheck = true; schemas.Compile(); var assembly = Assembly.GetExecutingAssembly(); using (Stream stream = assembly.GetManifestResourceStream(resourceName)) { var doc = new XmlDocument(); doc.Load(stream); doc.Schemas.Add(schemas); Debug.WriteLine(doc.OuterXml); Debug.WriteLine("------------------"); doc.Validate(((sender, args) => { Debug.WriteLine("{0} {1}", args.Message, args.Severity); Assert.Fail(args.Message); })); } }
public static void LoadCompositionSchema(System.Xml.Schema.XmlSchemaSet xs) { if (!xs.Contains(OpenEhrNamespace)) { System.Xml.Schema.XmlSchema compositionSchema = GetOpenEhrSchema("Composition"); System.Xml.Schema.XmlSchema contentSchema = GetOpenEhrSchema("Content"); compositionSchema.Includes.RemoveAt(0); foreach (System.Xml.Schema.XmlSchemaObject item in contentSchema.Items) { compositionSchema.Items.Add(item); } System.Xml.Schema.XmlSchema structureSchema = GetOpenEhrSchema("Structure"); foreach (System.Xml.Schema.XmlSchemaObject item in structureSchema.Items) { compositionSchema.Items.Add(item); } System.Xml.Schema.XmlSchema baseTypesSchema = GetOpenEhrSchema("BaseTypes"); foreach (System.Xml.Schema.XmlSchemaObject item in baseTypesSchema.Items) { compositionSchema.Items.Add(item); } xs.Add(compositionSchema); xs.Compile(); } }
public static void LoadEhrStatusSchema(System.Xml.Schema.XmlSchemaSet xs) { if (!xs.Contains(OpenEhrNamespace)) { System.Xml.Schema.XmlSchema ehrStatusSchema = GetOpenEhrSchema("EhrStatus"); ehrStatusSchema.Includes.RemoveAt(0); System.Xml.Schema.XmlSchema structureSchema = GetOpenEhrSchema("Structure"); foreach (System.Xml.Schema.XmlSchemaObject item in structureSchema.Items) { ehrStatusSchema.Items.Add(item); } System.Xml.Schema.XmlSchema baseTypesSchema = GetOpenEhrSchema("BaseTypes"); foreach (System.Xml.Schema.XmlSchemaObject item in baseTypesSchema.Items) { ehrStatusSchema.Items.Add(item); } xs.Add(ehrStatusSchema); xs.Compile(); } }
public bool ProcessSchema(string filePath) { if(String.IsNullOrWhiteSpace(filePath)) { return false; } var schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); schemaSet.Add("urn:newrelic-config", filePath); schemaSet.Compile(); XmlSchema schema = null; foreach (XmlSchema TempSchema in schemaSet.Schemas()) { schema = TempSchema; } var configurationElement = schema.Items[0] as XmlSchemaElement; if (configurationElement != null) { ProcessElement(configurationElement, null); ConfigurationFile.Xsd.RootElement = true; } return true; }
private SchemaSet() { var schemaDir = Path.Combine(ApplicationInformation.Directory, RelativeSchemaDir); if (!SchemaHasBeenCopied(schemaDir)) { try { if (Directory.Exists(schemaDir)) { Directory.Delete(schemaDir, true); } Directory.CreateDirectory(schemaDir); var assembly = GetType().Assembly; var schemaResourcePrefix = string.Format("{0}.Resources.Schema.", assembly.GetName().Name); var resources = assembly.GetManifestResourceNames(); foreach (var resource in resources.Where(r => r.StartsWith(schemaResourcePrefix))) { var filename = Path.Combine(schemaDir, resource.Replace(schemaResourcePrefix, string.Empty)); using (var stream = new FileStream(filename, FileMode.CreateNew)) { using (var manifestStream = assembly.GetManifestResourceStream(resource)) { manifestStream.CopyTo(stream); } } } } catch (Exception err) { logger.ErrorFormat(Messages.Loader_Loader_FailedToLoadAndCompileSchema, err); throw; } } Schemas = new XmlSchemaSet(); Schemas.Add(Globals.JdfNamespace.NamespaceName, Path.Combine(schemaDir, "jdf.xsd")); Schemas.Compile(); }
protected override object CoreGetSourceObject(string sourceFilePath, IDictionary<string, IList<string>> properties) { XmlSchemaSet xmlSchemaSet; XmlSchema xmlSchema; ObjectConstruct objectConstruct00; if ((object)sourceFilePath == null) throw new ArgumentNullException("sourceFilePath"); if ((object)properties == null) throw new ArgumentNullException("properties"); if (DataType.IsWhiteSpace(sourceFilePath)) throw new ArgumentOutOfRangeException("sourceFilePath"); sourceFilePath = Path.GetFullPath(sourceFilePath); objectConstruct00 = new ObjectConstruct(); using (Stream stream = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) xmlSchema = XmlSchema.Read(stream, ValidationCallback); xmlSchemaSet = new XmlSchemaSet(); xmlSchemaSet.Add(xmlSchema); xmlSchemaSet.Compile(); xmlSchema = xmlSchemaSet.Schemas().Cast<XmlSchema>().ToList()[0]; EnumSchema(objectConstruct00, xmlSchema.Items); return objectConstruct00; }
public ClrMappingInfo GenerateMapping(XmlSchemaSet schemas) { if (schemas == null) { throw new ArgumentNullException("schemas"); } schemas.ValidationEventHandler += new ValidationEventHandler(Validationcallback); schemas.Compile(); this.schemas = schemas; if (schemaErrorCount > 0) { Console.WriteLine("Schema cannot be compiled. Class generation aborted"); return null; } // Execute transformations try { Xml.Fxt.FxtLinq2XsdInterpreter.Run(schemas, configSettings.trafo); } catch (Xml.Fxt.FxtException) { Console.WriteLine("Schema cannot be transformed. Class generation aborted"); return null; } return GenerateMetaModel(); }
public SchemaValidator(string schemaNamespace, string schemaPath) { if (schemaNamespace == null) { throw new ArgumentNullException("schemaNamespace"); } if (schemaNamespace.Length == 0) { throw new ArgumentException("schema namespace cannot be zero length!"); } if (schemaPath == null) { throw new ArgumentNullException("schemaPath"); } if (schemaPath.Length == 0) { throw new ArgumentException("schemaPath cannot be of zero length!"); } if (!File.Exists(schemaPath)) { throw new ArgumentException("Schema: " + schemaPath + " cannot be located!"); } schemaSet = new XmlSchemaSet(); schemaSet.Add(schemaNamespace, schemaPath); schemaSet.Compile(); }
private static XmlSchemaSet CreateSchema() { var schemas = new XmlSchemaSet { XmlResolver = new ResourceXmlResolver() }; schemas.Add(DDEXSchemaLoader.LoadSchema("release-notification.xsd")); schemas.Compile(); return schemas; }
public void Add () { XmlSchemaSet ss = new XmlSchemaSet (); XmlDocument doc = new XmlDocument (); doc.LoadXml ("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' />"); ss.Add (null, new XmlNodeReader (doc)); // null targetNamespace ss.Compile (); // same document, different targetNamespace ss.Add ("ab", new XmlNodeReader (doc)); // Add(null, xmlReader) -> targetNamespace in the schema doc.LoadXml ("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='urn:foo' />"); ss.Add (null, new XmlNodeReader (doc)); Assert.AreEqual (3, ss.Count); bool chameleon = false; bool ab = false; bool urnfoo = false; foreach (XmlSchema schema in ss.Schemas ()) { if (schema.TargetNamespace == null) chameleon = true; else if (schema.TargetNamespace == "ab") ab = true; else if (schema.TargetNamespace == "urn:foo") urnfoo = true; } Assert.IsTrue (chameleon, "chameleon schema missing"); Assert.IsTrue (ab, "target-remapped schema missing"); Assert.IsTrue (urnfoo, "target specified in the schema ignored"); }
public void ValidXmlDoc(string xml, XmlReader xsd) { if (string.IsNullOrEmpty(xml)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "The argument '{0}' is Null or Empty", "xml")); } if (xsd == null) { throw new ArgumentNullException("xsd"); } try { XmlSchemaSet sc = new XmlSchemaSet(); sc.Add(null, xsd); sc.Compile(); XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas = sc; settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); XmlReader reader; using (StringReader stringReader = new StringReader(xml)) { reader = XmlReader.Create(stringReader, settings); while (reader.Read()); } } catch (Exception ex) { this.validationError = ex.Message; isValidXml = false; } }
public void v3(object param0, object param1, object param2, object param3, object param4) { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); sc.Add((string)param3, TestData._Root + param1.ToString()); CError.Compare(sc.Count, 1, "AddCount"); CError.Compare(sc.IsCompiled, false, "AddIsCompiled"); sc.Compile(); CError.Compare(sc.Count, 1, "CompileCount"); CError.Compare(sc.IsCompiled, true, "CompileIsCompiled"); XmlSchema parent = sc.Add(null, TestData._Root + param0.ToString()); CError.Compare(sc.Count, param2, "Add2Count"); CError.Compare(sc.IsCompiled, false, "Add2IsCompiled"); // check that schema is present in parent.Includes and its NS correct. foreach (XmlSchemaImport imp in parent.Includes) if (imp.SchemaLocation.Equals(param1.ToString()) && imp.Schema.TargetNamespace == (string)param4) return; Assert.True(false); }
public IEnumerable<string> Validate(string fpml) { _failureMessages = new List<string>(); var xdoc = XDocument.Parse(fpml); //TODO - this would be a lookup to allow multiple schema versions: var version = "5-7"; var schemaLocation = @".\schema\fpml\reporting-merged-schema-5-7\fpml-main-5-7.xsd"; var reader = xdoc.CreateReader(); reader.Read(); if (!_SchemaSets.ContainsKey(version)) { lock (_SchemaSetLock) { var schemaSet = new XmlSchemaSet(reader.NameTable); schemaSet.Add(@"http://www.fpml.org/FpML-5/reporting", schemaLocation); schemaSet.Compile(); _SchemaSets[version] = schemaSet; } } xdoc.Validate(_SchemaSets[version], (sender, args) => _failureMessages.Add(args.Message)); return _failureMessages; }
public static SDataSchema Read(TextReader reader, string targetElementName) { var xsd = XmlSchema.Read(reader, null); var schemaSet = new XmlSchemaSet(); schemaSet.Add(xsd); schemaSet.Compile(); var resources = new Dictionary<string, SDataResource>(); foreach (DictionaryEntry entry in xsd.Elements) { var name = (XmlQualifiedName) entry.Key; if (name.Namespace != xsd.TargetNamespace) { continue; } var resource = new SDataResource(); resource.Load(name, schemaSet); resources.Add(name.Name, resource); } return new SDataSchema { TargetElementName = targetElementName, Namespace = xsd.TargetNamespace, Resources = resources }; }
void IWsdlImportExtension.ImportContract (WsdlImporter importer, WsdlContractConversionContext context) { if (!enabled) return; if (importer == null) throw new ArgumentNullException ("importer"); if (context == null) throw new ArgumentNullException ("context"); if (this.importer != null || this.context != null) throw new SystemException ("INTERNAL ERROR: unexpected recursion of ImportContract method call"); dc_importer = new XsdDataContractImporter (); schema_set_in_use = new XmlSchemaSet (); schema_set_in_use.Add (importer.XmlSchemas); foreach (WSDL wsdl in importer.WsdlDocuments) foreach (XmlSchema xs in wsdl.Types.Schemas) schema_set_in_use.Add (xs); // commenting out this import operation, but might be required (I guess not). //dc_importer.Import (schema_set_in_use); schema_set_in_use.Compile (); this.importer = importer; this.context = context; try { DoImportContract (); } finally { this.importer = null; this.context = null; } }
/// <summary> /// Формируем XmlSchema для правильного отображения индикаторов группы в VGridControl /// </summary> /// <param name="elmList">названия всех по</param> /// <returns>Возвращаем поток в который записана XmlSchema</returns> public static MemoryStream CreateXmlSchemaForIndicatorsInGroup(List<string[]> elmList) { var xmlSchema = new XmlSchema(); // <xs:element name="root"> var elementRoot = new XmlSchemaElement(); xmlSchema.Items.Add(elementRoot); elementRoot.Name = "root"; // <xs:complexType> var complexType = new XmlSchemaComplexType(); elementRoot.SchemaType = complexType; // <xs:choice minOccurs="0" maxOccurs="unbounded"> var choice = new XmlSchemaChoice(); complexType.Particle = choice; choice.MinOccurs = 0; choice.MaxOccursString = "unbounded"; // <xs:element name="record"> var elementRecord = new XmlSchemaElement(); choice.Items.Add(elementRecord); elementRecord.Name = "record"; // <xs:complexType> var complexType2 = new XmlSchemaComplexType(); elementRecord.SchemaType = complexType2; // <xs:sequence> var sequence = new XmlSchemaSequence(); complexType2.Particle = sequence; foreach (var el in elmList) { var element = new XmlSchemaElement(); sequence.Items.Add(element); element.Name = el[0]; element.SchemaTypeName = new XmlQualifiedName(el[1], "http://www.w3.org/2001/XMLSchema"); } var schemaSet = new XmlSchemaSet(); schemaSet.Add(xmlSchema); schemaSet.Compile(); XmlSchema compiledSchema = null; foreach (XmlSchema schema1 in schemaSet.Schemas()) compiledSchema = schema1; var nsmgr = new XmlNamespaceManager(new NameTable()); nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); var ms = new MemoryStream(); if (compiledSchema != null) compiledSchema.Write(ms, nsmgr); ms.Position = 0; return ms; }
static ReadonlyContactProperties() { _contactSchemaCache = new XmlSchemaSet(); Uri contactXsdUri = ContactUtil.GetResourceUri("contact.xsd"); var schema = XmlSchema.Read(Application.GetResourceStream(contactXsdUri).Stream, _OnValidationError); _contactSchemaCache.Add(schema); _contactSchemaCache.Compile(); }
public void v2(object param0, object param1, object param2, object param3, object param4, object param5) { string ns1 = param0.ToString(); string ns2 = param3.ToString(); string type1 = param1.ToString(); string type2 = param2.ToString(); string type3 = param4.ToString(); string type4 = param5.ToString(); XmlSchema s1 = GetSchema(ns1, type1, type2); XmlSchema s2 = GetSchema(ns2, type3, type4); XmlSchemaSet ss = new XmlSchemaSet(); ss.Add(s1); CError.Compare(ss.GlobalTypes.Count, 0, "Types Count after add"); ss.Compile(); ss.Add(s2); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after add/compile"); //+1 for anyType ss.Compile(); //Verify CError.Compare(ss.GlobalTypes.Count, 5, "Types Count after add/compile/add/compile"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns1)), true, "Contains2"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type3, ns2)), true, "Contains3"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type4, ns2)), true, "Contains4"); //Now reprocess one schema and check ss.Reprocess(s1); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after repr"); //+1 for anyType ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 5, "Types Count after repr/comp"); //+1 for anyType //Now Remove one schema and check ss.Remove(s1); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after remove"); ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after remove/comp"); return; }
public static void AddElementToSchema(XmlSchema xmlSchema, string elementName, string elementType, string xmlNamespace) { XmlSchemaElement testNode = new XmlSchemaElement(); testNode.Name = elementName; testNode.Namespaces.Add("", xmlNamespace); testNode.SchemaTypeName = new XmlQualifiedName(elementType, xmlNamespace); xmlSchema.Items.Add(testNode); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.Add(xmlSchema); schemaSet.Compile(); }
public static XmlSchemaSet SchemasFromDescrip(IEnumerable<ServiceDescription> descriptions) { var schemaSet = new XmlSchemaSet(); var soap = new StringReader(string.Format(Properties.Resources.SoapSchema, descriptions.First().TargetNamespace)); schemaSet.Add(XmlSchema.Read(soap, new ValidationEventHandler(Validation))); foreach (var schema in descriptions.SelectMany(d => d.Types.Schemas.OfType<XmlSchema>())) { schemaSet.Add(schema); } schemaSet.Compile(); return schemaSet; }
public void v2() { XmlSchemaSet sc = new XmlSchemaSet(); sc.Add("xsdauthor1", TestData._XsdNoNs); CError.Compare(sc.IsCompiled, false, "IsCompiled after first add"); sc.Compile(); CError.Compare(sc.IsCompiled, true, "IsCompiled after compile"); sc.Add("xsdauthor", TestData._XsdAuthor); CError.Compare(sc.IsCompiled, false, "IsCompiled after seciond add"); sc.Compile(); CError.Compare(sc.IsCompiled, true, "IsCompiled after second compile"); return; }
public void v3() { XmlSchemaSet sc = new XmlSchemaSet(); sc.Add("xsdauthor1", TestData._XsdNoNs); XmlSchema Schema1 = sc.Add("xsdauthor", TestData._XsdAuthor); sc.Compile(); sc.Remove(Schema1); CError.Compare(sc.IsCompiled, false, "IsCompiled after compiled and remove"); return; }
/// <summary> /// Create a precompiled XMLSchemaSet. /// </summary> /// <param name="schemaName"></param> /// <param name="schemas"></param> /// <returns></returns> public static XmlSchemaSet CreateXmlSchemaSet(string schemaName, Dictionary<string, byte[]> schemas) { //Create and compile XmlSchemaSet using (var _XSDReader = new XmlTextReader(new MemoryStream(schemas[schemaName]))) { var _schemaSet = new XmlSchemaSet(); _schemaSet.XmlResolver = new SchemaResolver(schemas); _schemaSet.Add(null, _XSDReader); _schemaSet.Compile(); return _schemaSet; } }
public void v2(object param0, object param1, object param2, object param3, object param4, object param5) { string ns1 = param0.ToString(); string ns2 = param3.ToString(); string a1 = param1.ToString(); string a2 = param2.ToString(); string a3 = param4.ToString(); string a4 = param5.ToString(); XmlSchema s1 = GetSchema(ns1, a1, a2); XmlSchema s2 = GetSchema(ns2, a3, a4); XmlSchemaSet ss = new XmlSchemaSet(); ss.Add(s1); ss.Compile(); ss.Add(s2); CError.Compare(ss.GlobalAttributes.Count, 2, "Elements Countafter add"); //+1 for anyType ss.Compile(); //Verify CError.Compare(ss.GlobalAttributes.Count, 4, "Elements Count after add/compile"); CError.Compare(ss.GlobalAttributes.Contains(new XmlQualifiedName(a1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalAttributes.Contains(new XmlQualifiedName(a2, ns1)), true, "Contains2"); CError.Compare(ss.GlobalAttributes.Contains(new XmlQualifiedName(a3, ns2)), true, "Contains3"); CError.Compare(ss.GlobalAttributes.Contains(new XmlQualifiedName(a4, ns2)), true, "Contains4"); //Now reprocess one schema and check ss.Reprocess(s1); ss.Compile(); CError.Compare(ss.GlobalAttributes.Count, 4, "Elements Count after reprocess"); //Now Remove one schema and check ss.Remove(s1); CError.Compare(ss.GlobalAttributes.Count, 2, "Elements Count after remove no compile"); ss.Compile(); CError.Compare(ss.GlobalAttributes.Count, 2, "Elements Count adter remove and compile"); return; }
private static XmlSchemaSet ReadXmlSchemaFromEmbeddedResource(string resourceName) { Assembly executingAssembly = Assembly.GetExecutingAssembly(); using (Stream resourceStream = executingAssembly.GetManifestResourceStream(resourceName)) { var xmlSchema = XmlSchema.Read(resourceStream, null); var xmlSchemaSet = new XmlSchemaSet(); xmlSchemaSet.Add(xmlSchema); xmlSchemaSet.Compile(); return xmlSchemaSet; } }
// CanImport public bool CanImport (XmlSchemaSet schemas) { if (schemas == null) throw new ArgumentNullException ("schemas"); if (!schemas.IsCompiled) schemas.Compile (); foreach (XmlSchemaElement xe in schemas.GlobalElements.Values) if (!CanImport (schemas, xe)) return false; return true; }
protected XmlSchemaValidator CreateValidator(string xsdFilename, string targetNamespace, XmlSchemaValidationFlags flags) { string path = xsdFilename; XmlSchemaSet schemas = new XmlSchemaSet(); schemas.XmlResolver = new XmlUrlResolver(); if (!path.StartsWith("file://") && !path.StartsWith("http://")) path = Path.Combine(this.TestData, path); schemas.Add(targetNamespace, path); schemas.Compile(); return CreateValidator(schemas, flags); }
/// <summary> /// /// </summary> /// <remarks></remarks> /// <seealso cref=""/> public void Read() { string path = Path.Combine(AppConfiguration.GetModuleWorkspacePath("DCM"), "Metadata", "schema.xsd"); //string path = Path.Combine(AppConfiguration.GetModuleWorkspacePath("DCM"), "Metadata", "ABCD", "ABCD_2.06.XSD"); //string path = Path.Combine(AppConfiguration.GetModuleWorkspacePath("DCM"), "Metadata", "eml", "eml.xsd"); XmlTextReader xsd_file = new XmlTextReader(path); XmlSchema schema_file = new XmlSchema(); schema_file = XmlSchema.Read(xsd_file, ValidationCallback); // Add the customer schema to a new XmlSchemaSet and compile it. // Any schema validation warnings and errors encountered reading or // compiling the schema are handled by the ValidationEventHandler delegate. XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); schemaSet.Add(schema_file); schemaSet.Compile(); // Retrieve the compiled XmlSchema object from the XmlSchemaSet // by iterating over the Schemas property. XmlSchema customerSchema = null; foreach (XmlSchema schema in schemaSet.Schemas()) { customerSchema = schema; } // Iterate over each XmlSchemaElement in the Values collection // of the Elements property. foreach (XmlSchemaElement element in customerSchema.Elements.Values) { readXmlSchemaElement(element, null); } Debug.WriteLine("-------------------------------------------------"); Debug.WriteLine("-------------metadataAttributeNames--------------"); Debug.WriteLine("-------------------------------------------------"); if (metadataAttributeNames.Count > 0) { metadataAttributeNames.ForEach(p => Debug.WriteLine(p)); } Debug.WriteLine("-------------metadataPackageNames--------------"); Debug.WriteLine("-------------------------------------------------"); if (metadataPackageNames.Count > 0) { metadataPackageNames.ForEach(p => Debug.WriteLine(p)); } Debug.WriteLine("-------------------------------------------------"); Debug.WriteLine("Packages :" + packages); Debug.WriteLine("PackagesAsParents :" + metadataPackageNames.Count); Debug.WriteLine("Attributes :" + metadataAttributeNames.Count); }
public void v1(String testDir, String testFile, int expCount, int expCountGT, int expCountGE, int expCountGA) { Initialize(); string xsd = Path.Combine(path, testDir, testFile); XmlSchemaSet ss = new XmlSchemaSet(); XmlSchema Schema = XmlSchema.Read(XmlReader.Create(xsd), ValidationCallback); ss.XmlResolver = new XmlUrlResolver(); XmlSchema Schema1 = ss.Add(Schema); ValidateSchemaSet(ss, expCount, false, 0, 0, 0, "Validation after add"); ValidateWithSchemaInfo(ss); ss.Compile(); ValidateSchemaSet(ss, expCount, true, expCountGT, expCountGE, expCountGA, "Validation after add/comp"); ValidateWithSchemaInfo(ss); XmlSchema Schema2 = null; foreach (XmlSchema schema in ss.Schemas()) Schema2 = ss.Reprocess(schema); ValidateSchemaSet(ss, expCount, false, 1, 0, 0, "Validation after repr"); ValidateWithSchemaInfo(ss); ss.Compile(); ValidateSchemaSet(ss, expCount, true, expCountGT, expCountGE, expCountGA, "Validation after repr/comp"); ValidateWithSchemaInfo(ss); Assert.Equal(ss.RemoveRecursive(Schema), true); ValidateSchemaSet(ss, 0, false, 1, 0, 0, "Validation after remRec"); ValidateWithSchemaInfo(ss); ss.Compile(); ValidateSchemaSet(ss, 0, true, 0, 0, 0, "Validation after remRec/comp"); ValidateWithSchemaInfo(ss); return; }
private static XmlSchemaSet compileXhtmlSchema() { var assembly = typeof(XHtml).Assembly; XmlSchemaSet schemas = new XmlSchemaSet(); var schema = new StringReader(Properties.Resources.fhir_xhtml); schemas.Add(null, XmlReader.Create(schema)); // null = use schema namespace as specified in schema file schema = new StringReader(Properties.Resources.xml); schemas.Add(null, XmlReader.Create(schema)); // null = use schema namespace as specified in schema file schemas.Compile(); return schemas; }
/// <summary> /// produces a validator which validates XML AASX files. /// </summary> /// <returns>initialized validator</returns> public static XmlValidator NewXmlValidator() { // Load the schema files var files = GetSchemaResources(SerializationFormat.XML); if (files == null) { throw new InvalidOperationException("No XML schema files could be found in the resources."); } var xmlSchemaSet = new System.Xml.Schema.XmlSchemaSet(); xmlSchemaSet.XmlResolver = new System.Xml.XmlUrlResolver(); try { Assembly myAssembly = Assembly.GetExecutingAssembly(); foreach (var schemaFn in files) { using (Stream schemaStream = myAssembly.GetManifestResourceStream(schemaFn)) { using (XmlReader schemaReader = XmlReader.Create(schemaStream)) { xmlSchemaSet.Add(null, schemaReader); } } } } catch (Exception ex) { throw new FileNotFoundException( $"Error accessing embedded resource schema files: {ex.Message}"); } var newRecs = new AasValidationRecordList(); // set up messages xmlSchemaSet.ValidationEventHandler += (object sender, System.Xml.Schema.ValidationEventArgs e) => { newRecs.Add( new AasValidationRecord( AasValidationSeverity.Serialization, null, $"{e?.Exception?.LineNumber}, {e?.Exception?.LinePosition}: {e?.Message}")); }; // compile try { xmlSchemaSet.Compile(); } catch (Exception ex) { throw new InvalidOperationException( $"Error compiling schema files: {ex.Message}"); } if (newRecs.Count > 0) { var parts = new List <string> { $"Failed to compile the schema files:" }; parts.AddRange(newRecs.Select <AasValidationRecord, string>((r) => r.Message)); throw new InvalidOperationException(string.Join(Environment.NewLine, parts)); } return(new XmlValidator(xmlSchemaSet)); }
/// <summary> /// Load the schema from an XSD into this XmlSchema object /// </summary> /// <param name="SchemaLocation">The location of the schema to import</param> public void Load() { // Load the schema into the schema set try { ss.Compile(); // Iterate through types and create them int i = 0; namespaces.Clear(); // clear namespaces // Determine target namespace string targetNs = ""; foreach (System.Xml.Schema.XmlSchema s in ss.Schemas()) { if (targetNs != s.TargetNamespace && s.TargetNamespace != null) { targetNs = s.TargetNamespace; break; } } targetNamespace = targetNs; foreach (Object o in ss.GlobalTypes.Values) { if (o is System.Xml.Schema.XmlSchemaComplexType) { RegisterComplexType((System.Xml.Schema.XmlSchemaComplexType)o); } else if (o is System.Xml.Schema.XmlSchemaSimpleType) { RegisterSimpleType((System.Xml.Schema.XmlSchemaSimpleType)o); } // Alert for update if (Loading != null) { Loading(this, ((float)i / ((float)ss.GlobalTypes.Count * 2))); } i++; } // Iterate through root elements and create them foreach (Object o in ss.GlobalElements.Values) { if (o is System.Xml.Schema.XmlSchemaElement) { RegisterElement((System.Xml.Schema.XmlSchemaElement)o); } } // Iterate through types and compile them for (int p = 0; p < Types.Count; p++) { XmlSchemaType t = Types[p]; if (t is XmlSchemaComplexType) { (t as XmlSchemaComplexType).Compile(); } // Alert for update if (Loading != null) { Loading(this, ((float)i / ((float)Types.Count * 2))); } i++; } types.Sort(new XmlSchemaComparison()); } catch (Exception e) { throw new System.Xml.Schema.XmlSchemaException(String.Format("Can not compile the schemas - {0}", e.Message), e); } }