private static void Validate(XDocument doc, XmlSchemaSet xmlScheme) { bool notValidated = false; doc.Validate(xmlScheme, (eventObject, eventHandler) => { notValidated = true; }, false); Console.WriteLine(notValidated ? "Not Validated" : "Validated"); }
XmlSchemaSet genSchema(string xmlName) { XmlReader reader = XmlReader.Create (@xmlName); XmlSchemaSet schemaSet = new XmlSchemaSet (); XmlSchemaInference schema = new XmlSchemaInference (); schemaSet = schema.InferSchema (reader); return schemaSet; }
public static XmlQualifiedName WaterMLSchema(XmlSchemaSet xs) { //// This method is called by the framework to get the schema for this type. //// We return an existing schema from disk. Assembly asmb = Assembly.GetExecutingAssembly(); string[] names = asmb.GetManifestResourceNames(); Stream stream = asmb.GetManifestResourceStream("WaterOneFlowImpl.JustVariableValue.xsd"); //string text = new StreamReader(stream).ReadToEnd(); // stream.Position = 0; XmlSchema vsvSchema = XmlSchema.Read(stream, null); xs.Add(vsvSchema); //XmlNameTable xmlNameTable = new NameTable(); //XmlSchemaSet xmlSchemaSet = new XmlSchemaSet(xmlNameTable); //xmlSchemaSet.Add(vsvSchema); //vsvSchema.Namespaces.Add("wtr10", "http://www.cuahsi.org/waterML/1.0/"); //XmlQualifiedName xmlQualifiedName = new XmlQualifiedName(TypeName, "http://www.cuahsi.org/waterML/1.0/"); //// XmlSchemaObject vsv = vsvSchema.Elements[xmlQualifiedName]; //XmlSchemaObject vsv = vsvSchema.SchemaTypes[xmlQualifiedName]; ////XmlSchema vsvSchema2 = new XmlSchema(); //vsvSchema2.Items.Add(vsv); //foreach (string VARIABLE in new String[] // { // "CensorCodeEnum", // "QualityControlLevelEnum", // }) //{ // XmlQualifiedName qn = new XmlQualifiedName(VARIABLE, "http://www.cuahsi.org/waterML/1.0/"); // vsvSchema2.Items.Add(vsvSchema.SchemaTypes[qn]); // } //foreach (var VARIABLE in new String[] // { // "ValueAttr","DbIdentifiers","offsetAttr" // }) //{ // XmlQualifiedName qn = new XmlQualifiedName(VARIABLE, "http://www.cuahsi.org/waterML/1.0/"); // vsvSchema2.Items.Add(vsvSchema.AttributeGroups[qn]); //} //vsvSchema2.Namespaces.Add("", "http://www.cuahsi.org/waterML/1.0/"); //xs.XmlResolver = new XmlUrlResolver(); //xs.Add(vsvSchema2); return new XmlQualifiedName(TypeName, "http://www.cuahsi.org/waterML/1.0/"); }
static XmlReader CreateValidatingReader(Stream stream, XmlSchemaSet schemas, ValidationEventHandler eventHandler) { XmlReaderSettings settings = new XmlReaderSettings(); settings.Schemas.Add(schemas); settings.ValidationType = ValidationType.Schema; if (eventHandler != null) settings.ValidationEventHandler += eventHandler; return XmlReader.Create(stream, settings); }
static void Main() { XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add("", "../../16. Catalog.xsd"); XDocument doc = XDocument.Load("../../../1. Catalog.xml"); // you can try to change the xml file to see the warnings string msg = ""; doc.Validate(schemas, (o, e) => { msg = e.Message; }); Console.WriteLine(msg == "" ? "Document is valid" : "Document invalid: " + msg); }
static void Main() { var xmlScheme = new XmlSchemaSet(); xmlScheme.Add(string.Empty, @"..\..\..\catalogue.xsd"); XDocument doc = XDocument.Load(@"..\..\..\catalogue.xml"); XDocument notValidDoc = XDocument.Load(@"..\..\..\notValidCatalogue.xml"); Console.WriteLine("The valid catalogue XML result:"); Validate(doc, xmlScheme); Console.WriteLine("The notValidCatalogue XML result:"); Validate(notValidDoc, xmlScheme); }
static void Test2 () { XmlSchemaSet schemaSet = new XmlSchemaSet (); schemaSet.Add (null, "test.xsd"); XmlReaderSettings settings = new XmlReaderSettings (); settings.ValidationType = ValidationType.Schema; settings.CloseInput = true; settings.Schemas.Add (schemaSet); XmlReader r = XmlReader.Create ("test.xml", settings); XPathDocument d = new XPathDocument (r); d.CreateNavigator (); }
static void Main () { string dir = AppDomain.CurrentDomain.BaseDirectory; using (Stream input = File.OpenRead (Path.Combine (dir, "test.xml"))) { #if NET_2_0 XmlSchemaSet schemas = new XmlSchemaSet (); #else XmlSchemaCollection schemas = new XmlSchemaCollection (); #endif schemas.Add (XmlSchema.Read (File.OpenRead (Path.Combine (dir, "spring-objects.xsd")), null)); XmlReader reader = CreateValidatingReader (input, schemas, null); XmlDocument doc = new XmlDocument (); doc.Load (reader); } }
protected void Page_Load(object sender, EventArgs e) { string booksSchemaFile = Server.MapPath("books.xsd"); string booksFile = Server.MapPath("books.xml"); XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add(null, XmlReader.Create(booksSchemaFile)); XDocument booksXML = XDocument.Load(booksFile); booksXML.Validate(schemas, (senderParam, eParam) => { Response.Write(eParam.Message); }, true); XNamespace ns = "http://example.books.com"; var books = from book in booksXML.Descendants(ns + "book") select book.Element(ns + "title").Value; Response.Write(String.Format("Found {0} books!", books.Count())); }
static int Main () { XmlSchema schema = XmlSchema.Read (new XmlTextReader ("schema.xsd"), null); #if NET_2_0 XmlReaderSettings settings = new XmlReaderSettings (); settings.ValidationType = ValidationType.None; XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.Add(schema); XmlReader reader = XmlReader.Create (new StringReader (xml), settings); XmlNamespaceManager manager = new XmlNamespaceManager (reader.NameTable); XmlSchemaValidator validator = new XmlSchemaValidator (reader.NameTable, schemaSet, manager, XmlSchemaValidationFlags.None); validator.Initialize (); validator.ValidateElement ("test", string.Empty, null); try { validator.ValidateAttribute ("mode", string.Empty, "NOT A ENUMERATION VALUE", null); return 1; } catch (XmlSchemaValidationException) { } finally { reader.Close (); } #else XmlValidatingReader validator = new XmlValidatingReader (xml, XmlNodeType.Document, null); validator.ValidationType = ValidationType.Schema; validator.Schemas.Add (schema); try { while (validator.Read ()) ; return 1; } catch (XmlSchemaException) { } finally { validator.Close (); } #endif return 0; }
void IWsdlImportExtension.BeforeImport(ServiceDescriptionCollection wsdlDocuments, XmlSchemaSet xmlSchemas, ICollection <XmlElement> policy) { }
public static void Main() { XmlSchema schema = new XmlSchema(); // <xs:element name="cat" type="string"/> XmlSchemaElement elementCat = new XmlSchemaElement(); schema.Items.Add(elementCat); elementCat.Name = "cat"; elementCat.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); // <xs:element name="dog" type="string"/> XmlSchemaElement elementDog = new XmlSchemaElement(); schema.Items.Add(elementDog); elementDog.Name = "dog"; elementDog.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); // <xs:element name="redDog" substitutionGroup="dog" /> XmlSchemaElement elementRedDog = new XmlSchemaElement(); schema.Items.Add(elementRedDog); elementRedDog.Name = "redDog"; elementRedDog.SubstitutionGroup = new XmlQualifiedName("dog"); // <xs:element name="brownDog" substitutionGroup ="dog" /> XmlSchemaElement elementBrownDog = new XmlSchemaElement(); schema.Items.Add(elementBrownDog); elementBrownDog.Name = "brownDog"; elementBrownDog.SubstitutionGroup = new XmlQualifiedName("dog"); // <xs:element name="pets"> XmlSchemaElement elementPets = new XmlSchemaElement(); schema.Items.Add(elementPets); elementPets.Name = "pets"; // <xs:complexType> XmlSchemaComplexType complexType = new XmlSchemaComplexType(); elementPets.SchemaType = complexType; // <xs:choice minOccurs="0" maxOccurs="unbounded"> XmlSchemaChoice choice = new XmlSchemaChoice(); complexType.Particle = choice; choice.MinOccurs = 0; choice.MaxOccursString = "unbounded"; // <xs:element ref="cat"/> XmlSchemaElement catRef = new XmlSchemaElement(); choice.Items.Add(catRef); catRef.RefName = new XmlQualifiedName("cat"); // <xs:element ref="dog"/> XmlSchemaElement dogRef = new XmlSchemaElement(); choice.Items.Add(dogRef); dogRef.RefName = new XmlQualifiedName("dog"); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne); schemaSet.Add(schema); schemaSet.Compile(); XmlSchema compiledSchema = null; foreach (XmlSchema schema1 in schemaSet.Schemas()) { compiledSchema = schema1; } XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); compiledSchema.Write(Console.Out, nsmgr); }
public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { XmlQualifiedName qualifiedName = new XmlQualifiedName("base64Binary", "http://www.w3.org/2001/XMLSchema"); return(qualifiedName); }
public XmlValidationConstraint WithSchema(XmlSchemaSet schemas) { this.schemaSet.Add(schemas); return(this); }
public static XmlSchemaComplexType GetTypedTableSchema(XmlSchemaSet xs) { XmlSchemaComplexType xmlSchemaComplexType; XmlSchema xmlSchema; XmlSchemaComplexType type = new XmlSchemaComplexType(); XmlSchemaSequence sequence = new XmlSchemaSequence(); guard_profiles_dbDataSet ds = new guard_profiles_dbDataSet(); XmlSchemaAny any1 = new XmlSchemaAny() { Namespace = "http://www.w3.org/2001/XMLSchema", MinOccurs = new decimal(0), MaxOccurs = new decimal(-1, -1, -1, false, 0), ProcessContents = XmlSchemaContentProcessing.Lax }; sequence.Items.Add(any1); XmlSchemaAny any2 = new XmlSchemaAny() { Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1", MinOccurs = new decimal(1), ProcessContents = XmlSchemaContentProcessing.Lax }; sequence.Items.Add(any2); XmlSchemaAttribute attribute1 = new XmlSchemaAttribute() { Name = "namespace", FixedValue = ds.Namespace }; type.Attributes.Add(attribute1); XmlSchemaAttribute attribute2 = new XmlSchemaAttribute() { Name = "tableTypeName", FixedValue = "Tbl_sg_profilesDataTable" }; type.Attributes.Add(attribute2); type.Particle = sequence; XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { MemoryStream s1 = new MemoryStream(); MemoryStream s2 = new MemoryStream(); try { XmlSchema schema = null; dsSchema.Write(s1); IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); while (schemas.MoveNext()) { schema = (XmlSchema)schemas.Current; s2.SetLength((long)0); schema.Write(s2); if (s1.Length != s2.Length) { continue; } s1.Position = (long)0; s2.Position = (long)0; while (s1.Position != s1.Length && s1.ReadByte() == s2.ReadByte()) { } if (s1.Position != s1.Length) { continue; } xmlSchemaComplexType = type; return(xmlSchemaComplexType); } xmlSchema = xs.Add(dsSchema); return(type); } finally { if (s1 != null) { s1.Close(); } if (s2 != null) { s2.Close(); } } return(xmlSchemaComplexType); } xmlSchema = xs.Add(dsSchema); return(type); }
public void XmlSchemaValidatorDoesNotEnforceIdentityConstraintsOnDefaultAttributesInSomeCases() { Initialize(); string xml = @"<?xml version='1.0'?> <root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='idF016.xsd'> <uid val='test'/> <uid/></root>" ; string xsd = @"<?xml version='1.0'?> <xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' elementFormDefault='qualified'> <xsd:element name='root'> <xsd:complexType> <xsd:sequence> <xsd:element ref='uid' maxOccurs='unbounded'/> </xsd:sequence> </xsd:complexType> <xsd:unique id='foo123' name='uuid'> <xsd:selector xpath='.//uid'/> <xsd:field xpath='@val'/> </xsd:unique> </xsd:element> <xsd:element name='uid' nillable='true'> <xsd:complexType> <xsd:attribute name='val' type='xsd:string' default='test'/> </xsd:complexType> </xsd:element> </xsd:schema>"; XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable()); XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add(null, XmlReader.Create(new StringReader(xsd))); schemas.Compile(); XmlSchemaValidationFlags validationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.AllowXmlAttributes; XmlSchemaValidator validator = new XmlSchemaValidator(namespaceManager.NameTable, schemas, namespaceManager, validationFlags); validator.Initialize(); using (XmlReader r = XmlReader.Create(new StringReader(xsd))) { while (r.Read()) { switch (r.NodeType) { case XmlNodeType.Element: namespaceManager.PushScope(); if (r.MoveToFirstAttribute()) { do { if (r.NamespaceURI == "http://www.w3.org/2000/xmlns/") { namespaceManager.AddNamespace(r.LocalName, r.Value); } } while (r.MoveToNextAttribute()); r.MoveToElement(); } validator.ValidateElement(r.LocalName, r.NamespaceURI, null, null, null, null, null); if (r.MoveToFirstAttribute()) { do { if (r.NamespaceURI != "http://www.w3.org/2000/xmlns/") { validator.ValidateAttribute(r.LocalName, r.NamespaceURI, r.Value, null); } } while (r.MoveToNextAttribute()); r.MoveToElement(); } validator.ValidateEndOfAttributes(null); if (r.IsEmptyElement) { goto case XmlNodeType.EndElement; } break; case XmlNodeType.EndElement: validator.ValidateEndElement(null); namespaceManager.PopScope(); break; case XmlNodeType.Text: validator.ValidateText(r.Value); break; case XmlNodeType.SignificantWhitespace: case XmlNodeType.Whitespace: validator.ValidateWhitespace(r.Value); break; default: break; } } validator.EndValidation(); } XmlReaderSettings rs = new XmlReaderSettings(); rs.ValidationType = ValidationType.Schema; rs.Schemas.Add(null, XmlReader.Create(new StringReader(xsd))); using (XmlReader r = XmlReader.Create(new StringReader(xml), rs)) { try { while (r.Read()) { ; } } catch (XmlSchemaValidationException e) { _output.WriteLine(e.Message); return; } } Assert.True(false); }
internal List <Uri> GetAddOnUriList() { // Get list of AddOn URLs HashSet <string> nameSpaceUriSet = new HashSet <string>(); List <Uri> addOnUri = new List <Uri>(); foreach (Fact fact in XBRLModel.FactList) { if (!nameSpaceUriSet.Contains(fact.Item.Name.NamespaceName)) { nameSpaceUriSet.Add(fact.Item.Name.NamespaceName); } } XmlSchemaSet schemaSet = XBRLModel.Schemas; foreach (XmlSchema schema in schemaSet.Schemas()) { if (nameSpaceUriSet.Contains(schema.TargetNamespace)) { Uri uri = new Uri(schema.SourceUri); string filename = System.IO.Path.GetFileName(uri.LocalPath); if (filename.EndsWith(".xsd")) { foreach (XElement element in _xDoc.Descendants("TaxonomyAddon")) { XElement taxonomyElement = element.Element("Taxonomy"); if (taxonomyElement.Value == filename) { Logger.Info(taxonomyElement.Value); string addOnFile; Uri newUri; if (element.Element("DefinitionFiles") != null) { addOnFile = element.Element("DefinitionFiles").Element("string").Value; newUri = new Uri(uri, addOnFile); addOnUri.Add(newUri); Logger.Info(newUri.AbsoluteUri); } if (element.Element("ReferenceFiles") != null) { addOnFile = element.Element("ReferenceFiles").Element("string").Value; newUri = new Uri(uri, addOnFile); addOnUri.Add(newUri); Logger.Info(newUri.AbsoluteUri); } } } } } } return(addOnUri); }
private int XmlValid(string XmlName, string XmlNS, string XmlXsd) { // Create the XmlSchemaSet class. int errValid = 0; XmlSchemaSet sc = new XmlSchemaSet(); StreamReader readerTxt = new StreamReader(XmlName); //string[] tmp = new string[255]; ArrayList tmp = new ArrayList(); int tmpI = 0; while (!readerTxt.EndOfStream) { tmp.Add(readerTxt.ReadLine()); } string LeftSide = ""; string rightSide = ""; string middle = "xmlns=\"" + XmlNS + "\""; string totalRep = ""; string ReplaceStr = tmp[1].ToString(); char[] replaceChars = ReplaceStr.ToCharArray(); char sp = char.Parse(" "); char rt = char.Parse(">"); int j = 0; while (replaceChars[j] != sp && replaceChars[j] != rt) { LeftSide += replaceChars[j]; j++; } while (j < replaceChars.Length) { rightSide += replaceChars[j]; j++; } totalRep += LeftSide + " " + middle + rightSide; using (StreamWriter writer = new StreamWriter(Path.GetTempPath() + "tmpXML.xml")) { writer.WriteLine(tmp[0].ToString()); writer.WriteLine(totalRep); tmpI = 2; while (tmpI < tmp.Count) { writer.WriteLine(tmp[tmpI].ToString()); //tmp[tmpI] = readerTxt.ReadLine(); tmpI++; } writer.Close(); } //root.AppendChild(Attribute ) //if (root.Attributes[0].Value.ToString() != XmlNS ) //{ // errValid++; // return errValid; //} //Console.WriteLine(root.Attributes[0].Value); // Add the schema to the collection. sc.Add(XmlNS, XmlXsd); // Set the validation settings. XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas = sc; settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); // Create the XmlReader object. XmlReader reader = XmlReader.Create(Path.GetTempPath() + "tmpXML.xml", settings); // Parse the file. while (reader.Read()) { ; } if (XmlValidity != 0) { XmlValidity = 0; errValid++; reader.Close(); File.Delete(Path.GetTempPath() + "tmpXML.xml"); return(errValid); } else { XmlValidity = 0; errValid = 0; reader.Close(); File.Delete(Path.GetTempPath() + "tmpXML.xml"); return(errValid); } return(errValid); }
public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return(new XmlQualifiedName("short", XmlSchema.Namespace)); }
public void WhenTheValidatorIsCalledWithInvalidXmlTheErrorEventIsFired() { var customerSchema = xsdFilePaths.FirstOrDefault(w => w.ToLower().Contains("customersorders.xsd")); var customerXml = xmlFilePaths.FirstOrDefault(w => w.ToLower().Contains("customersorderswitherror.xml")); if (customerSchema == null) { Assert.Fail("CustomersOrders.xsd File Missing"); } if (customerXml == null) { Assert.Fail("customersorderswitherror.xml File Missing"); } xmlSchemaReader = new XmlSchemaReader(fileSystem, memoryStreamFactory); var schema = xmlSchemaReader.ReadFromPath(customerSchema); var schemaSet = new XmlSchemaSet { XmlResolver = new XmlUrlResolver() }; schemaSet.Add(schema); if (schema == null) { Assert.Fail("Schema could not be loaded"); } var validator = new XmlValidator(memoryStreamFactory, fileSystem, null, null, null, null, null); var errors = new List <ValidationErrorEventArgs>(); var methodHasBeenCalled = false; var count = 0; validator.ErrorOccurred += async(s, e, c) => { await Task.Run(() => { errors.Add(e); methodHasBeenCalled = true; }); }; var res = validator.ValidateXmlFileAgainstSchemaAsync(customerXml, schemaSet, true).Result; Thread.Sleep(1000); while (count < 10) { Thread.Sleep(1000); if (methodHasBeenCalled) { break; } count++; } Assert.IsTrue(methodHasBeenCalled); Assert.AreEqual(2, errors.Count); }
internal static XmlReader GetValidatingReader(XmlReader input, bool ignoreWhitespace, XmlSchemaSet schemaSet) { XmlReaderSettings settings = new XmlReaderSettings(); settings.CloseInput = true; settings.IgnoreComments = true; settings.IgnoreWhitespace = ignoreWhitespace; if (schemaSet != null) { settings.Schemas = schemaSet; settings.ValidationType = ValidationType.Schema; } return(XmlReader.Create(input, settings)); }
/// <summary> /// Processes the schema. /// </summary> /// <param name="xsdFile">The full path to the WXS file to process.</param> /// <param name="targetNamespace">The namespace to put generated classes in.</param> /// <returns>The CodeDom tree generated from the schema.</returns> public static CodeNamespace Process(string xsdFile, string targetNamespace, CodeDomProvider Provider) { // Load the XmlSchema and its collection. //XmlSchema xsd; //using ( FileStream fs = new FileStream( xsdFile, FileMode.Open ) ) //{ // xsd = XmlSchema.Read( fs, VH1 ); // xsd.Compile( VH2 ); //} XmlSchemaSet set = new XmlSchemaSet(); XmlSchema xsd = set.Add(null, xsdFile); set.Compile(); XmlSchemas schemas = new XmlSchemas(); schemas.Add(xsd); // Create the importer for these schemas. XmlSchemaImporter importer = new XmlSchemaImporter(schemas); // System.CodeDom namespace for the XmlCodeExporter to put classes in. CodeNamespace ns = new CodeNamespace(targetNamespace); XmlCodeExporter exporter = new XmlCodeExporter(ns); // Iterate schema top-level elements and export code for each. foreach (XmlSchemaElement element in set.GlobalElements.Values) { // Import the mapping first. XmlTypeMapping mapping = importer.ImportTypeMapping( element.QualifiedName); // Export the code finally. exporter.ExportTypeMapping(mapping); } #region Execute extensions XPathNavigator nav; using (FileStream fs = new FileStream(xsdFile, FileMode.Open, FileAccess.Read)) { nav = new XPathDocument(fs).CreateNavigator(); } XPathNodeIterator it = nav.Select(Extensions); while (it.MoveNext()) { Dictionary <string, string> values = ParsePEValue(it.Current.Value); Type t = Type.GetType(values["extension-type"], true); // Is the type an ICodeExtension? Type iface = t.GetInterface(typeof(ICodeExtension).Name); if (iface == null) { throw new ArgumentException(string.Format(Resources.ex_InvalidExtensionType, it.Current.Value)); } ICodeExtension ext = (ICodeExtension)Activator.CreateInstance(t); ext.Initialize(values); // Run it! ext.Process(ns, xsd, Provider); } #endregion Execute extensions return(ns); }
/// <summary> /// Creates a new <see cref="SparseReader"/> pointing to a <see cref="System.IO.Stream"/> rather /// than a <see cref="System.Xml.XmlReader"/>. /// </summary> /// <param name="dispatchTable">The dispatch table used to fire delegates for XML elements on /// this instance.</param> /// <param name="stream">The stream from which XML shall be retrieved. The SparseReader takes /// ownership of this stream and is responsible for destroying it.</param> /// <param name="schemaSet">The xml schema to validate the input against</param> /// <returns> /// A <see cref="SparseReader"/> wrapping the stream <paramref name="stream"/>. /// </returns> public static SparseReader CreateFromStream(SparseReaderDispatchTable dispatchTable, Stream stream, XmlSchemaSet schemaSet) { var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, CloseInput = true, Schemas = schemaSet }; XmlReader xReader = null; try { xReader = XmlReader.Create(stream, settings); xReader.MoveToContent(); // If this throws, we destroy the reader in the finally block below. var result = new SparseReader(dispatchTable, xReader); // nothrow xReader = null; // Ownership transfered to SparseReader; don't destroy here return(result); } finally { if (xReader != null) { xReader.Dispose(); } } }
/// <summary> /// Converts schemas to NodeTypes, AttributeTypes, and root elements</summary> /// <param name="schemaSet">Schemas to register</param> public void Load(XmlSchemaSet schemaSet) { if (!schemaSet.IsCompiled) { schemaSet.Compile(); } System.Collections.ICollection schemas = schemaSet.Schemas(); foreach (XmlSchema schema in schemas) { string targetNamespace = schema.TargetNamespace; if (string.IsNullOrEmpty(targetNamespace)) { throw new InvalidOperationException("Schema has no target namespace"); } // only register the schema once; targetNamespaces must be globally unique if (!m_typeCollections.ContainsKey(targetNamespace)) { XmlQualifiedName[] nameSpaces = schema.Namespaces.ToArray(); XmlSchemaTypeCollection typeCollection = new XmlSchemaTypeCollection(nameSpaces, targetNamespace, this); m_typeCollections.Add(targetNamespace, typeCollection); } } try { m_annotations = new Dictionary <NamedMetadata, IList <XmlNode> >(); m_typeNameSet = new HashSet <string>(); m_localElementSet = new Dictionary <XmlSchemaElement, XmlQualifiedName>(); // collect global element & type names so we do not generate local type names that collides with those foreach (XmlSchemaElement element in schemaSet.GlobalElements.Values) { m_typeNameSet.Add(element.QualifiedName.Name); } foreach (XmlSchemaType type in schemaSet.GlobalTypes.Values) { if (type is XmlSchemaComplexType) { m_typeNameSet.Add(type.Name); } } var substitutionGroups = new Multimap <XmlQualifiedName, ChildInfo>(); // Get types reachable from global elements foreach (XmlSchemaElement element in schemaSet.GlobalElements.Values) { XmlSchemaType type = element.ElementSchemaType; DomNodeType nodeType = GetNodeType(type, element); ChildInfo childInfo = new ChildInfo(GetFieldName(element.QualifiedName), nodeType); m_annotations.Add(childInfo, GetAnnotation(element)); // Keep list of substitution groups if (!element.SubstitutionGroup.IsEmpty) { substitutionGroups.Add(element.SubstitutionGroup, childInfo); } // only add root elements once; root element names must be globally unique string name = element.QualifiedName.ToString(); if (!m_rootElements.ContainsKey(name)) { m_rootElements[name] = childInfo; } } // Get global complex type definitions foreach (XmlSchemaType type in schemaSet.GlobalTypes.Values) { if (type is XmlSchemaComplexType) { GetNodeType(type, null); } } // Parse substitution groups foreach (var kvp in m_refElements) { XmlQualifiedName refName = kvp.Value; ChildInfo childInfo = kvp.Key; var substitutions = CreateSubstitutions(substitutionGroups, refName).ToArray(); if (substitutions.Length > 0) { childInfo.AddRule(new SubstitutionGroupChildRule(substitutions)); } } // Preserve annotation from any types that were redefined foreach (XmlSchema schema in schemas) { foreach (XmlSchemaObject schemaInclude in schema.Includes) { XmlSchemaRedefine schemaRedefine = schemaInclude as XmlSchemaRedefine; if (schemaRedefine != null) { MergeRedefinedTypeAnnotations(schemaRedefine); } } } // Sort DomNodeTypes, so that base types are always before derived types // Bucket sort by depth in the inheritance tree // Time: O(n * d) with n = number of DomNodeTypes, d = depth of inheritance tree var sortedTypes = new List <List <DomNodeType> >(); foreach (DomNodeType type in GetNodeTypes()) { // Get inheritance depth of current type int depth = 0; DomNodeType curType = type; while (curType != null && curType != DomNodeType.BaseOfAllTypes) { depth++; curType = curType.BaseType; } // We don't need to merge annotations for BaseAllTypes (level 0) // and its immediate child types (level 1) int idx = depth - 2; if (idx >= 0) { while (sortedTypes.Count <= idx) { sortedTypes.Add(new List <DomNodeType>()); } sortedTypes[idx].Add(type); } } // Merge type annotations with base type annotations foreach (var list in sortedTypes) { foreach (DomNodeType type in list) { if (type.BaseType != null && type.BaseType != DomNodeType.BaseOfAllTypes) { IList <XmlNode> baseAnnotations; IList <XmlNode> annotations; if (m_annotations.TryGetValue(type.BaseType, out baseAnnotations) && m_annotations.TryGetValue(type, out annotations)) { // Call protected virtual merge method - allowing clients to define if & how annotations are being merged IEnumerable <XmlNode> mergedAnnotations = MergeInheritedTypeAnnotations(baseAnnotations, annotations); m_annotations[type] = mergedAnnotations as IList <XmlNode> ?? mergedAnnotations.ToList(); } } } } // Call before the DomNodeTypes are frozen. Note that iterating through Attributes or // calling 'SetIdAttribute' freezes the attributes on DomNodeType. OnSchemaSetLoaded(schemaSet); // Set up ID attributes where xs:ID has been specified foreach (DomNodeType nodeType in GetNodeTypes()) { foreach (var attribute in nodeType.Attributes.OfType <XmlAttributeInfo>()) { if (((XmlAttributeType)attribute.Type).XmlTypeCode == XmlTypeCode.Id) { nodeType.SetIdAttribute(attribute.Name); } } } // Attach annotation as metadata to the associated type so that other classes can find it foreach (var keyValuePair in m_annotations) { if (keyValuePair.Value.Count > 0) { keyValuePair.Key.SetTag <IEnumerable <XmlNode> >(keyValuePair.Value); } } ParseAnnotations(schemaSet, m_annotations); // Call this after the ID attributes have been set and after the DomNodeTypes are frozen. OnDomNodeTypesFrozen(schemaSet); } finally { m_annotations = null; m_typeNameSet = null; m_localElementSet = null; } }
public XsdApiTypesMetadataFactory(XmlSchemaSet schemaSet) : base(schemaSet) { }
/// <summary> /// GetTableSchema For WebService /// </summary> public static XmlSchemaComplexType getTableSchema(XmlSchemaSet xs) { var dt = new AL_AssmblingLogDataTable(); return(getTableSchema(xs, dt, "ALAL")); }
internal static void ProcessCompositionXml(Stream configurationStream, XmlProcessingContext xmlProcessingContext) { if (configurationStream == null) { throw new ArgumentNullException(nameof(configurationStream)); } var xsdStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( "Appson.Composer.CompositionXml.Schema.compositionXml.1.0.xsd"); if (xsdStream == null) { throw new NullReferenceException("Could not load XSD resource from DLL."); } var schema = XmlSchema.Read( xsdStream, delegate(object sender, ValidationEventArgs e) { throw new CompositionXmlValidationException( "Could not load XSD for Composition XML. Message: " + e.Message + "; Sender: " + sender, e.Exception); }); var schemaSet = new XmlSchemaSet(); schemaSet.Add(schema); var settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, Schemas = schemaSet }; settings.ValidationEventHandler += delegate(object sender, ValidationEventArgs e) { var errorMessage = "Composition XML Schema Validation error: "; var validationException = e.Exception as XmlSchemaValidationException; if (validationException != null) { errorMessage += "Line: " + validationException.LineNumber + ", Position: " + validationException.LinePosition + "; " + validationException.Message; } else { errorMessage += "Message: " + e.Message + "; Sender: " + sender + "; Inner exception: " + e.Exception.Message; } xmlProcessingContext.ReportError(errorMessage); }; var serializer = new XmlSerializer(typeof(CompositionInfo)); var reader = XmlReader.Create(configurationStream, settings); var info = (CompositionInfo)serializer.Deserialize(reader); info.Validate(); CompositionInfoApplicator.ApplyCompositionInfo(info, xmlProcessingContext); }
public static XmlSchemaComplexType GetTypedDataSetSchema(XmlSchemaSet xs) { XmlSchemaComplexType xmlSchemaComplexType; XmlSchema xmlSchema; guard_profiles_dbDataSet ds = new guard_profiles_dbDataSet(); XmlSchemaComplexType type = new XmlSchemaComplexType(); XmlSchemaSequence sequence = new XmlSchemaSequence(); XmlSchemaAny any = new XmlSchemaAny() { Namespace = ds.Namespace }; sequence.Items.Add(any); type.Particle = sequence; XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { MemoryStream s1 = new MemoryStream(); MemoryStream s2 = new MemoryStream(); try { XmlSchema schema = null; dsSchema.Write(s1); IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); while (schemas.MoveNext()) { schema = (XmlSchema)schemas.Current; s2.SetLength((long)0); schema.Write(s2); if (s1.Length != s2.Length) { continue; } s1.Position = (long)0; s2.Position = (long)0; while (s1.Position != s1.Length && s1.ReadByte() == s2.ReadByte()) { } if (s1.Position != s1.Length) { continue; } xmlSchemaComplexType = type; return(xmlSchemaComplexType); } xmlSchema = xs.Add(dsSchema); return(type); } finally { if (s1 != null) { s1.Close(); } if (s2 != null) { s2.Close(); } } return(xmlSchemaComplexType); } xmlSchema = xs.Add(dsSchema); return(type); }
/// <summary> /// Adds an <see cref="XmlSchema"/> instance for this type to the supplied <see cref="XmlSchemaSet"/>. /// </summary> /// <param name="xs">The <see cref="XmlSchemaSet"/> to add an <see cref="XmlSchema"/> to.</param> /// <returns>An <see cref="XmlQualifiedName"/> for the current object.</returns> public static XmlQualifiedName AcquireSchema(XmlSchemaSet xs) { return(new XmlQualifiedName("any", "http://www.w3.org/2001/XMLSchema")); }
public static XmlQualifiedName GetSchema(XmlSchemaSet schemaSet) { EndpointAddress10.GetSchema(schemaSet); schemaSet.Add(schema); return(new XmlQualifiedName("ProbeMatchType", version.Namespace)); }
public void Generate(UblGeneratorOptions options) { Console.WriteLine("Validating options..."); _options = options; options.Validate(); var baseInputDirectory = options.XsdBasePath; var maindocfiles = new List <FileInfo>(); if (!string.IsNullOrEmpty(baseInputDirectory)) { maindocfiles = new DirectoryInfo(baseInputDirectory).GetFiles("*.xsd").ToList(); } var maindocSchemaSet = new XmlSchemaSet() { // XmlResolver = xsdResolver // XmlResolver = null }; Console.WriteLine("Read common UBL files from embedded resources..."); var nameTable = new NameTable(); var readerSettings = new XmlReaderSettings { ValidationType = ValidationType.Schema, DtdProcessing = DtdProcessing.Parse, NameTable = nameTable }; AddCommonFiles(maindocSchemaSet, readerSettings); Console.WriteLine($"Add schema files from {baseInputDirectory}..."); var schemasToGenerate = new List <XmlSchema>(); foreach (var maindocfile in maindocfiles) { using (var reader = XmlReader.Create(maindocfile.FullName, readerSettings)) { var schema = XmlSchema.Read(reader, null); // ReplaceKnownSchemaIncludes(schema, knownSchema); maindocSchemaSet.Add(schema); schemasToGenerate.Add(schema); } } Console.WriteLine("Fixing schema..."); maindocSchemaSet.Compile(); foreach (var schemaFixer in _schemaFixers) { schemaFixer(maindocSchemaSet); maindocSchemaSet.Compile(); } Console.WriteLine("Creating compile unit..."); var namespaceProvider = new CodeNamespaceProvider(maindocSchemaSet, options); var compileUnit = CreateCodeNamespace(maindocSchemaSet, namespaceProvider); foreach (var ns in compileUnit.Namespaces.OfType <CodeNamespace>()) { _globalCodeFixer.Fix(ns); } var codeProvider = new CSharpCodeProvider(); var codegenOptions = new CodeGeneratorOptions() { BracingStyle = "C", IndentString = " ", BlankLinesBetweenMembers = true, VerbatimOrder = true }; Console.WriteLine("Generating source files..."); if (options.GenerateCommonFiles) { foreach (var schema in maindocSchemaSet.Schemas().Cast <XmlSchema>()) { GenerateCodeForSchema(options, compileUnit, namespaceProvider, codeProvider, codegenOptions, schema); } } else { foreach (var schema in schemasToGenerate) { GenerateCodeForSchema(options, compileUnit, namespaceProvider, codeProvider, codegenOptions, schema); } } }
/*Standard code for cloning*/ ///*Detach events*/ // object[] saved = Utils.DetachEvents(this); // /*Clone*/ // Workflow w = new Workflow(); // Utils.DeepCloneObject(this, w); // /*Registering the new workflow to his nodes*/ // foreach(WFnode nd in w.connectionGraph.Nodes){ // nd.FieldModified += w.nd_FieldModified; // nd.NodeNameModified += w.nd_NodeNameModified; // } // foreach (WFedgeLabel ed in w.connectionGraph.Edges) // { // ed.EdgeModified += w.ed_EdgeModified; // } // /*Reattach events*/ // Utils.ReattachEvents(this, saved); public static void Schema2RenderSync(XmlDocument renderDoc, XmlSchemaSet Schema, string nodeName) { }
// Constructors public XmlSchemaValidator(System.Xml.XmlNameTable nameTable, XmlSchemaSet schemas, System.Xml.IXmlNamespaceResolver namespaceResolver, XmlSchemaValidationFlags validationFlags) { }
public XmlValidationConstraint() { this.schemaValidator = new XmlValidator(); this.schemaSet = new XmlSchemaSet(); this.UseResolver(XmlGlobalsSettings.XmlResolver); }
private CodeCompileUnit CreateCodeNamespace(XmlSchemaSet schemaSet, CodeNamespaceProvider namespaceProvider) { var compileUnit = new CodeCompileUnit(); var schemas = new XmlSchemas(); foreach (var s in schemaSet.Schemas()) { schemas.Add((XmlSchema)s); } schemas.Compile(_options.ValidationHandler, true); foreach (XmlSchema schema in schemas) { var codeNamespace = namespaceProvider.CreateCodeNamespace(schema); compileUnit.Namespaces.Add(codeNamespace); } var codeOptions = CodeGenerationOptions.GenerateOrder | CodeGenerationOptions.GenerateNewAsync; // foreach (var ns in rootNamespaces.Concat(extensionNamespaces)) foreach (XmlSchema schema in schemas) { var schemaImporter = new XmlSchemaImporter(schemas); schemaImporter.Extensions.Clear(); // var schema = schemas[ns]; var codeNamespace = compileUnit.Namespaces.OfType <CodeNamespace>().Single(x => x.UserData[CodeTypeMemberExtensions.XmlSchemaKey] == schema); Console.WriteLine($"Import root namespace: {schema.TargetNamespace}"); var codeExporter = new XmlCodeExporter(codeNamespace, compileUnit, codeOptions); foreach (XmlSchemaElement element in schema.Elements.Values.OfType <XmlSchemaElement>()) { Console.WriteLine($"Import type mapping for {element.QualifiedName.Namespace} : {element.QualifiedName.Name}"); var xmlTypeMapping = schemaImporter.ImportTypeMapping(element.QualifiedName); codeExporter.ExportTypeMapping(xmlTypeMapping); } var baseTypes = schema.Elements.Values.OfType <XmlSchemaElement>().Select(x => x.SchemaTypeName.Name).ToList(); foreach (XmlSchemaComplexType element in schema.SchemaTypes.Values.OfType <XmlSchemaComplexType>().Where(x => !baseTypes.Contains(x.Name))) { Console.WriteLine($"Import schema type for {element.QualifiedName.Namespace} : {element.QualifiedName.Name}"); var xmlTypeMapping = schemaImporter.ImportSchemaType(element.QualifiedName); codeExporter.ExportTypeMapping(xmlTypeMapping); } } var codeDeclarations = compileUnit.Namespaces.OfType <CodeNamespace>().SelectMany(x => x.Types.Cast <CodeTypeDeclaration>()).ToList(); foreach (var codeDecl in codeDeclarations) { codeDecl.Comments.Clear(); foreach (var item in codeDecl.Members.OfType <CodeTypeMember>()) { item.Comments.Clear(); } var qname = codeDecl.GetQualifiedName(); codeDecl.UserData[CodeTypeMemberExtensions.QualifiedNameKey] = qname; // Note, this can fail when there are multiple schemas for one namespace, like urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2 var schema = schemas.GetSchemas(qname.Namespace).OfType <XmlSchema>().FirstOrDefault(); // var schema = schemas[qname.Namespace]; codeDecl.UserData[CodeTypeMemberExtensions.XmlSchemaKey] = schema; var xmlSchemaType = (XmlSchemaType)schema.SchemaTypes[qname]; codeDecl.UserData[CodeTypeMemberExtensions.XmlSchemaTypeKey] = xmlSchemaType; foreach (CodeTypeMember member in codeDecl.Members) { member.UserData[CodeTypeMemberExtensions.XmlSchemaKey] = schema; member.UserData[CodeTypeMemberExtensions.XmlSchemaTypeKey] = xmlSchemaType; } } return(compileUnit); }
public void BeforeImport(XmlSchemaSet xmlSchemas) { }
public void Add(XmlSchemaSet schemas) { }
/// <summary> /// Method called after the schema set has been loaded and the DomNodeTypes have been created, but /// before the DomNodeTypes have been frozen. This means that DomNodeType.SetIdAttribute, for example, has /// not been called on the DomNodeTypes. Is called shortly before OnDomNodeTypesFrozen.</summary> /// <param name="schemaSet">XML schema sets being loaded</param> protected virtual void OnSchemaSetLoaded(XmlSchemaSet schemaSet) { }
public void BeforeImport( ServiceDescriptionCollection wsdlDocuments, XmlSchemaSet xmlSchemas, ICollection <XmlElement> policy) { }
protected internal static void AddSchemas(XmlSchemaSet schemas) { schemas.Add(schemaSet); }
/// <summary> /// Is called after the schema set has been loaded and the DomNodeTypes have been frozen with /// their ID attributes set. Is called shortly after OnSchemaSetLoaded.</summary> /// <param name="schemaSet">XML schema sets being loaded</param> protected virtual void OnDomNodeTypesFrozen(XmlSchemaSet schemaSet) { }
public XmlValidatorBase() { this._errs = new ArrayList(); this._schemaSet = new XmlSchemaSet(); }
private static void Load_SDMX_Schemas(XmlSchemaSet Schemas) { Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.xml))); Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXCommon))); Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXMessage))); Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXStructure))); Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXGenericData))); Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXUtilityData))); Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXCompactData))); Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXCrossSectionalData))); Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXGenericMetadata))); Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXMetadataReport))); Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXRegistry))); Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXQuery))); }
private void FixImportAddresses(ServiceDescriptionCollection wsdls, ServiceDescription wsdlDoc, XmlSchemaSet schemas) { foreach (System.Web.Services.Description.Import import in wsdlDoc.Imports) { if (string.IsNullOrEmpty(import.Location)) { ServiceDescription description = wsdls[import.Namespace ?? string.Empty]; if (description != null) { string query = queryFromDoc[description]; import.Location = this.location + "?" + query; } } } if (wsdlDoc.Types != null) { foreach (XmlSchema schema in wsdlDoc.Types.Schemas) { this.FixImportAddresses(schemas, schema); } } }
public XmlSchemaSet InferSchema(System.Xml.XmlReader instanceDocument, XmlSchemaSet schemas) { }