static void Main (string [] args) { string schemaFile = "bug.xsd"; XmlTextReader treader = new XmlTextReader (schemaFile); XmlSchema sc = XmlSchema.Read (treader, null); sc.Compile (null); string page = "<body xmlns=\"" + sc.TargetNamespace + "\">" + "<div>" + "</div>" + "</body>"; System.Xml.XmlTextReader reader = new XmlTextReader (new StringReader (page)); try { XmlValidatingReader validator = new System.Xml.XmlValidatingReader (reader); validator.Schemas.Add (sc); validator.ValidationType = ValidationType.Schema; validator.EntityHandling = EntityHandling.ExpandCharEntities; while (validator.Read ()) { } } finally { reader.Close (); } }
public void TestEmptySchema () { string xml = "<root/>"; xvr = PrepareXmlReader (xml); xvr.ValidationType = ValidationType.Schema; xvr.Read (); // Is is missing schema component. }
public void TestSimpleValidation () { string xml = "<root/>"; xvr = PrepareXmlReader (xml); Assert.AreEqual (ValidationType.Auto, xvr.ValidationType); XmlSchema schema = new XmlSchema (); XmlSchemaElement elem = new XmlSchemaElement (); elem.Name = "root"; schema.Items.Add (elem); xvr.Schemas.Add (schema); xvr.Read (); // root Assert.AreEqual (ValidationType.Auto, xvr.ValidationType); xvr.Read (); // EOF xml = "<hoge/>"; xvr = PrepareXmlReader (xml); xvr.Schemas.Add (schema); try { xvr.Read (); Assert.Fail ("element mismatch is incorrectly allowed"); } catch (XmlSchemaException) { } xml = "<hoge xmlns='urn:foo' />"; xvr = PrepareXmlReader (xml); xvr.Schemas.Add (schema); try { xvr.Read (); Assert.Fail ("Element in different namespace is incorrectly allowed."); } catch (XmlSchemaException) { } }
private XPathDocument CreateAndCacheDocument(XmlReader r, bool supportSchemaDeterminedIDs) { string uri = r.BaseURI; XmlValidatingReader vr = null; if (supportSchemaDeterminedIDs) { vr = new IdAssuredValidatingReader(r); vr.ValidationType = ValidationType.Auto; } else { vr = new XmlValidatingReader(r); vr.ValidationType = ValidationType.None; } vr.EntityHandling = EntityHandling.ExpandEntities; vr.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(ValidationCallback); XPathDocument doc = new XPathDocument(vr, XmlSpace.Preserve); vr.Close(); lock(_cache) { if (!_cache.ContainsKey(uri)) _cache.Add(uri, new WeakReference(doc)); } return doc; }
public void ShouldGenerateASchemaToValidateTestSubClassXml() { NetReflectorTypeTable table = new NetReflectorTypeTable { typeof (TestClass), typeof (TestInnerClass), typeof (TestSubClass) }; XsdGenerator generator = new XsdGenerator(table); XmlSchema schema = generator.Generate(true); #if DEBUG schema.Write(Console.Out); #endif string xmlToValidate = TestClass.GetXmlWithSubClass(DateTime.Today); #if DEBUG Console.Out.WriteLine("xmlToValidate = {0}", xmlToValidate); #endif XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(new StringReader(xmlToValidate))); reader.Schemas.Add(schema); reader.ValidationType = ValidationType.Schema; while (reader.Read()) {} }
public static void ValidateSchema(string xml) { var schemaStream = typeof(HoptoadValidator).Assembly.GetManifestResourceStream("Tests.hoptoad_2_0.xsd"); var schema = XmlSchema.Read(schemaStream, (sender, args) => { }); var reader = new StringReader(xml); var xmlReader = new XmlTextReader(reader); #pragma warning disable 0618 var validator = new XmlValidatingReader(xmlReader); #pragma warning restore 0618 var errorBuffer = new StringBuilder(); validator.ValidationEventHandler += (sender, args) => { errorBuffer.AppendLine(args.Message); }; validator.Schemas.Add(schema); while (validator.Read()) { } if (errorBuffer.ToString().Length > 0) Assert.Fail(errorBuffer.ToString()); }
/*Validar archivo XML Contra Esquema XSD*/ public void Validar(string rutaFicheroXml) { var r = new XmlTextReader(rutaFicheroXml); var v = new XmlValidatingReader(r) {ValidationType = ValidationType.Schema}; v.ValidationEventHandler += ValidarControlEventos; var procesarXml = new ConvertirXmlEnTexo(); procesarXml.ProcesarArchivo(rutaFicheroXml/*,@"D:\pruebas.txt"*/); try { while (v.Read()) { } // Comprobar si el documento es válido o no. //return _isValid ? "true" : "false"; // var procesarXml = new ConvertirXmlEnTexo(); // procesarXml.ProcesarArchivo(rutaFicheroXml/*,@"D:\pruebas.txt"*/); v.Close(); } catch (Exception e) { //ValidarControlEventos(null, null); // _isValid = false; // MessageBox.Show("Evento de validación\r\n" + e.Message, @"Validacion de XML", // MessageBoxButtons.OK, MessageBoxIcon.Asterisk); ////v.ValidationEventHandler += new ValidationEventHandler(ValidarControlEventos); //return "true"; } }
protected void Page_Load(object sender, EventArgs e) { string xmlFile = Server.MapPath("~/Customers1.xml"); string xsdFile = Server.MapPath("~/Customers.xsd"); XmlTextReader textReader = new XmlTextReader(xmlFile); XmlValidatingReader validatingReader = new XmlValidatingReader(textReader); validatingReader.Schemas.Add(null, xsdFile); validatingReader.ValidationType = ValidationType.Schema; validatingReader.ValidationEventHandler += new ValidationEventHandler(validatingReader_ValidationEventHandler); while (validatingReader.Read()) { if (validatingReader.NodeType == XmlNodeType.Element) { if (validatingReader.SchemaType is XmlSchemaComplexType) { XmlSchemaComplexType complexType = (XmlSchemaComplexType)validatingReader.SchemaType; Response.Write(validatingReader.Name + " " + complexType.Name); } else { object innerText = validatingReader.ReadTypedValue(); Response.Write(validatingReader.Name + " : " + innerText.ToString() + " <br />"); } } } validatingReader.Close(); }
/// <summary> /// Creates new instance of <c>XIncludingReader</c> class with /// specified underlying <c>XmlReader</c> reader. /// </summary> /// <param name="reader">Underlying reader to read from</param> public XIncludingReader(XmlReader reader) { XmlTextReader xtr = reader as XmlTextReader; if (xtr != null) { XmlValidatingReader vr = new XmlValidatingReader(reader); vr.ValidationType = ValidationType.None; vr.EntityHandling = EntityHandling.ExpandEntities; vr.ValidationEventHandler += new ValidationEventHandler( ValidationCallback); _normalization = xtr.Normalization; _whiteSpaceHandling = xtr.WhitespaceHandling; _reader = vr; } else { _reader = reader; } _nameTable = reader.NameTable; _keywords = new XIncludeKeywords(NameTable); if (_reader.BaseURI != "") _topBaseUri = new Uri(_reader.BaseURI); else { _relativeBaseUri = false; _topBaseUri = new Uri(Assembly.GetExecutingAssembly().Location); } _readers = new Stack<XmlReader>(); _state = XIncludingReaderState.Default; }
/// <summary> /// Validate XML Format /// </summary> /// <param name="text">XML string</param> public static bool IsValidXML(string text) { bool errored; byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(text); MemoryStream stream = new MemoryStream(byteArray); XmlTextReader xmlr = new XmlTextReader(stream); XmlValidatingReader reader = new XmlValidatingReader(xmlr); try { while (reader.Read()) { ; } errored = false; } catch { errored = true; } finally { reader.Close(); } return !errored; }
/// <summary> /// Valida se um Xml está seguindo de acordo um Schema /// </summary> /// <param name="arquivoXml">Arquivo Xml</param> /// <param name="arquivoSchema">Arquivo de Schema</param> /// <returns>True se estiver certo, Erro se estiver errado</returns> public void ValidaSchema(String arquivoXml, String arquivoSchema) { //Seleciona o arquivo de schema de acordo com o schema informado //arquivoSchema = Bll.Util.ContentFolderSchemaValidacao + "\\" + arquivoSchema; //Verifica se o arquivo de XML foi encontrado. if (!File.Exists(arquivoXml)) throw new Exception("Arquivo de XML informado: \"" + arquivoXml + "\" não encontrado."); //Verifica se o arquivo de schema foi encontrado. if (!File.Exists(arquivoSchema)) throw new Exception("Arquivo de schema: \"" + arquivoSchema + "\" não encontrado."); // Cria um novo XMLValidatingReader var reader = new XmlValidatingReader(new XmlTextReader(new StreamReader(arquivoXml))); // Cria um schemacollection var schemaCollection = new XmlSchemaCollection(); //Adiciona o XSD e o namespace schemaCollection.Add("http://www.portalfiscal.inf.br/nfe", arquivoSchema); // Adiciona o schema ao ValidatingReader reader.Schemas.Add(schemaCollection); //Evento que retorna a mensagem de validacao reader.ValidationEventHandler += Reader_ValidationEventHandler; //Percorre o XML while (reader.Read()) { } reader.Close(); //Fecha o arquivo. //O Resultado é preenchido no reader_ValidationEventHandler if (validarResultado != "") { throw new Exception(validarResultado); } }
private Hashtable helpNamespaceCache ; // a hashtable to improve lookup speeds /// <summary> /// Creates a new instance of the NamespaceMapper class based on the specified map file /// </summary> /// <param name="path">Path to the map file</param> public NamespaceMapper( string path ) { if ( !schemaIsValid ) throw new Exception( "The namespaceMap schema is not valid or could not be found" ); if ( !File.Exists( path ) ) throw new ArgumentException( string.Format( "{0} could not be found", path ), "path" ); XmlValidatingReader reader = new XmlValidatingReader( new XmlTextReader( path ) ); try { reader.Schemas.Add( namespaceMapSchema ); XmlDocument doc = new XmlDocument(); doc.Load( reader ); map = doc.DocumentElement; Debug.Assert( map != null ); } finally { reader.Close(); } helpNamespaceCache = new Hashtable(); }
public static WebReferenceOptions Read(XmlReader xmlReader, ValidationEventHandler validationEventHandler) { WebReferenceOptions options; XmlValidatingReader reader = new XmlValidatingReader(xmlReader) { ValidationType = ValidationType.Schema }; if (validationEventHandler != null) { reader.ValidationEventHandler += validationEventHandler; } else { reader.ValidationEventHandler += new ValidationEventHandler(WebReferenceOptions.SchemaValidationHandler); } reader.Schemas.Add(Schema); webReferenceOptionsSerializer serializer = new webReferenceOptionsSerializer(); try { options = (WebReferenceOptions) serializer.Deserialize(reader); } catch (Exception exception) { throw exception; } finally { reader.Close(); } return options; }
public static T_SeamateItems ParseItemsConfiguration(String configPath) { TextReader tr = null; XmlTextReader xml = null; XmlValidatingReader validate = null; xml = new XmlTextReader(configPath); validate = new XmlValidatingReader(xml); validate.ValidationEventHandler += new ValidationEventHandler(xsdValidationHandler); while (validate.Read()) { } validate.Close(); try { tr = new StreamReader(configPath); XmlSerializer serializer = new XmlSerializer(typeof(T_SeamateItems)); T_SeamateItems config = (T_SeamateItems)serializer.Deserialize(tr); tr.Close(); return config; } catch (Exception ex) { if (tr != null) { tr.Close(); } throw new Exception("Unable to read configuration file: " + configPath, ex); } return null; }
public GReader(string path) { document = new XmlDocument (); try { XmlTextReader textreader = new XmlTextReader (path); XmlValidatingReader vreader = new XmlValidatingReader (textreader); // Set the validation event handler vreader.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack); // Load the XML to Document node. document.Load (textreader); Console.WriteLine ("Validation finished. Validation {0}", (m_success==true ? "successful!" : "failed.")); //Close the reader. vreader.Close(); } catch (FileNotFoundException e) { Console.WriteLine ("Error: {0} not found.", e.FileName); Environment.Exit (1); } catch (DirectoryNotFoundException) { Console.WriteLine ("Error: {0} not found.", path); Environment.Exit (1); } catch (XmlException) { Console.WriteLine ("Error: {0} is not well-formed xml.", path); Environment.Exit (1); } }
public BaseCodeGenerator(Stream sourceXML) { XmlDocument doc = new XmlDocument(); using (sourceXML) { doc.Load(sourceXML); } MemoryStream ms = new MemoryStream(); doc.Save(ms); ms.Position = 0; using (XmlTextReader r = new XmlTextReader(ms)) { XmlValidatingReader v = new XmlValidatingReader(r); v.ValidationType = ValidationType.Schema; v.ValidationEventHandler += new ValidationEventHandler(v_ValidationEventHandler); while (v.Read()) { } v.Close(); } if (m_errors) throw new InvalidDataException("The Xml input did not match the schema"); Parse(doc); }
public static DefaultHighlightingStrategy Parse(SyntaxMode syntaxMode, XmlTextReader xmlTextReader) { try { XmlValidatingReader validatingReader = new XmlValidatingReader(xmlTextReader); Stream shemaStream = Assembly.GetCallingAssembly().GetManifestResourceStream("Mode.xsd"); validatingReader.Schemas.Add("", new XmlTextReader(shemaStream)); validatingReader.ValidationType = ValidationType.Schema; validatingReader.ValidationEventHandler += new ValidationEventHandler (ValidationHandler); XmlDocument doc = new XmlDocument(); doc.Load(validatingReader); DefaultHighlightingStrategy highlighter = new DefaultHighlightingStrategy(doc.DocumentElement.Attributes["name"].InnerText); if (doc.DocumentElement.Attributes["extensions"]!= null) { highlighter.Extensions = doc.DocumentElement.Attributes["extensions"].InnerText.Split(new char[] { ';', '|' }); } /* if (doc.DocumentElement.Attributes["indent"]!= null) { highlighter.DoIndent = Boolean.Parse(doc.DocumentElement.Attributes["indent"].InnerText); } */ XmlElement environment = doc.DocumentElement["Environment"]; highlighter.SetDefaultColor(new HighlightBackground(environment["Default"])); foreach (string aColorName in environmentColors) { highlighter.SetColorFor(aColorName, new HighlightColor(environment[aColorName])); } // parse properties if (doc.DocumentElement["Properties"]!= null) { foreach (XmlElement propertyElement in doc.DocumentElement["Properties"].ChildNodes) { highlighter.Properties[propertyElement.Attributes["name"].InnerText] = propertyElement.Attributes["value"].InnerText; } } if (doc.DocumentElement["Digits"]!= null) { highlighter.SetColorFor("Digits", new HighlightColor(doc.DocumentElement["Digits"])); } XmlNodeList nodes = doc.DocumentElement.GetElementsByTagName("RuleSet"); foreach (XmlElement element in nodes) { highlighter.AddRuleSet(new HighlightRuleSet(element)); } xmlTextReader.Close(); if(errors!=null) { ReportErrors(syntaxMode.FileName); errors = null; return null; } else { return highlighter; } } catch (Exception) { //MessageBox.Show("Could not load mode definition file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); return null; } }
private void PrepareReader1 (string xsdUrl, string xml) { schema = XmlSchema.Read (new XmlTextReader ("Test/XmlFiles/XsdValidation/" + xsdUrl), null); xr = new XmlTextReader (xml, XmlNodeType.Document, null); xvr = new XmlValidatingReader (xr); xvr.Schemas.Add (schema); // xvr = xr as XmlValidatingReader; }
public NSTScorePartwise ParseString(string dataString) { //todo: parse string IList<NSTPart> partList = new List<NSTPart>(); XmlTextReader textReader = new XmlTextReader(new FileStream("C:\\NM\\ScoreTranscription\\NETScoreTranscription\\NETScoreTranscriptionLibrary\\OtherDocs\\musicXML.xsd", System.IO.FileMode.Open)); //todo: pass stream in instead of absolute location for unit testing XmlSchemaCollection schemaCollection = new XmlSchemaCollection(); schemaCollection.Add(null, textReader); NSTScorePartwise score; using (XmlValidatingReader reader = new XmlValidatingReader(XmlReader.Create(new StringReader(dataString), new XmlReaderSettings() { DtdProcessing = DtdProcessing.Parse }))) //todo: make unobsolete { reader.Schemas.Add(schemaCollection); reader.ValidationType = ValidationType.Schema; reader.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(ValidationEventHandler); XmlSerializer serializer = new XmlSerializer(typeof(NSTScorePartwise), new XmlRootAttribute("score-partwise")); score = (NSTScorePartwise)serializer.Deserialize(reader); /* while (reader.Read()) { if (reader.IsEmptyElement) throw new Exception(reader.Value); //todo: test switch (reader.NodeType) { case XmlNodeType.Element: switch (reader.Name.ToLower()) { case "part-list": break; case "score-partwise": break; case "part-name": throw new Exception("pn"); break; } break; case XmlNodeType.Text: break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: break; case XmlNodeType.Comment: break; case XmlNodeType.EndElement: break; } }*/ } return score; }
protected override XmlValidatingReader GetXmlValidatingReaderForStream(XmlReader reader) { XmlValidatingReader validReader = new XmlValidatingReader(reader); validReader.ValidationType = ValidationType.Schema; validReader.Schemas.Add(XmlSchema.Read(Assembly .GetExecutingAssembly() .GetManifestResourceStream("resource.ruleml-0_86-datalog.xsd"), null)); return validReader; }
public static void Validate(XmlReader reader) { XmlValidatingReader vr = new XmlValidatingReader(reader); vr.ValidationType = ValidationType.Auto; vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler); while (vr.Read()){}; }
public string FilterFragment(string origHtmlFragment) { origHtmlFragment = CleanupHtml(origHtmlFragment); // Remove duplicate ids because they are invalid but not an attack vector. string htmlFragment = RemoveIds(origHtmlFragment); // Resolve general entities to character entities so we don't have to use // 2 XmlValidatingReaders - one with a DTD to resolve the general entities // and one with the schema to validate the document. htmlFragment = ResolveGeneralEntities(htmlFragment); string page = @"<html xmlns=""" + FilterInfo.Schema.TargetNamespace + @"""><head><title>title</title></head>" + "<body>" + "<div>\n" + htmlFragment + "\n</div>" + "</body>" + "</html>"; XmlTextReader reader = new XmlTextReader(new StringReader(page)); try { XmlValidatingReader validator = new System.Xml.XmlValidatingReader(reader); validator.ValidationEventHandler += new ValidationEventHandler(OnValidationError); validator.Schemas.Add(FilterInfo.Schema); validator.ValidationType = ValidationType.Schema; validator.EntityHandling = EntityHandling.ExpandCharEntities; while (validator.Read()) { } } finally { reader.Close(); } if (FilterInfo.UriAndStyleValidator != null) { reader = new XmlTextReader(new StringReader(page)); try { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load(reader); FilterInfo.UriAndStyleValidator.Validate(doc); } finally { reader.Close(); } } return(origHtmlFragment); }
static void Main(string[] args) { if (args.Length != 4) { Console.WriteLine("Invalid parameter count. Exiting..."); return; } string xmlFile = args[0]; string xdsFile = args[1]; string xdsNamespace = args[2]; string outputFile = args[3]; try { XmlSchemaCollection cache = new XmlSchemaCollection(); cache.Add(xdsNamespace, xdsFile); XmlTextReader r = new XmlTextReader(xmlFile); XmlValidatingReader v = new XmlValidatingReader(r); v.Schemas.Add(cache); v.ValidationType = ValidationType.Schema; v.ValidationEventHandler += new ValidationEventHandler(MyValidationEventHandler); while (v.Read()) { } // look for validation errors v.Close(); } catch (Exception e) { encounteredFatalError = true; fatalError = e; } StreamWriter file = new StreamWriter(outputFile); if (isValid && !encounteredFatalError) file.WriteLine("PASSED: Document is valid"); else file.WriteLine("FAILED: Document is invalid"); // Printing foreach (string entry in list) { file.WriteLine(entry); } if (encounteredFatalError) { file.WriteLine("Error: a FATAL error has occured " + "while reading the file.\r\n" + fatalError.ToString()); } file.Close(); }
static void Main(string[] args) { XmlTextReader r = new XmlTextReader(@"..\..\XMLFile1.xml"); XmlValidatingReader v = new XmlValidatingReader(r); v.ValidationType = ValidationType.Schema; v.ValidationEventHandler += new ValidationEventHandler(MyValidationEventHandler); while(v.Read()) { // Can add code here to process the content. } v.Close(); // Check whether the document is valid or invalid. if(m_isValid) { Console.WriteLine("Document is valid"); } else { Console.WriteLine("Document is invalid"); } /* XmlTextWriter xtw = new XmlTextWriter(new StreamWriter("test1.xml")); xtw.WriteStartDocument(true); xtw.WriteStartElement("MapVals"); xtw.WriteStartElement("MapValKey1"); xtw.WriteAttributeString("val1","a"); xtw.WriteAttributeString("val2","b"); xtw.WriteEndElement(); xtw.WriteStartElement("MapValKey2"); xtw.WriteAttributeString("val1","qf"); xtw.WriteAttributeString("val2","xt"); xtw.WriteEndElement(); xtw.WriteStartElement("MapValKey3"); xtw.WriteAttributeString("val1","wwu"); xtw.WriteAttributeString("val2","verble"); xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.WriteEndDocument(); xtw.Close(); */ }
/// <summary> /// Gets an appropriate <see cref="System.Xml.XmlReader"/> implementation /// for the supplied <see cref="System.IO.Stream"/>. /// </summary> /// <param name="stream">The XML <see cref="System.IO.Stream"/> that is going to be read.</param> /// <param name="xmlResolver"><see cref="XmlResolver"/> to be used for resolving external references</param> /// <param name="schemas">XML schemas that should be used for validation.</param> /// <param name="eventHandler">Validation event handler.</param> /// <returns> /// A validating <see cref="System.Xml.XmlReader"/> implementation. /// </returns> public static XmlReader CreateValidatingReader(Stream stream, XmlResolver xmlResolver, XmlSchemaCollection schemas, ValidationEventHandler eventHandler) { XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(stream)); reader.XmlResolver = xmlResolver; reader.Schemas.Add(schemas); reader.ValidationType = ValidationType.Schema; if (eventHandler != null) { reader.ValidationEventHandler += eventHandler; } return reader; }
public XPathDocument (string uri, XmlSpace space) { XmlValidatingReader vr = null; try { vr = new XmlValidatingReader (new XmlTextReader (uri)); vr.ValidationType = ValidationType.None; Initialize (vr, space); } finally { if (vr != null) vr.Close (); } }
private void Page_Load(object sender, System.EventArgs e) { XmlValidatingReader reader = null; XmlSchemaCollection myschema = new XmlSchemaCollection(); ValidationEventHandler eventHandler = new ValidationEventHandler(ShowCompileErrors ); try { String xmlFrag = @"<?xml version='1.0' ?> <item> <xxx:price xmlns:xxx='xxx' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='test.xsd'></xxx:price> </item>"; /*"<author xmlns='urn:bookstore-schema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" + "<first-name>Herman</first-name>" + "<last-name>Melville</last-name>" + "</author>";*/ string xsd = @"<?xml version='1.0' encoding='UTF-8'?> <xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' targetNamespace='xxx'> <xsd:element name='price' type='xsd:integer' xsd:default='12'/> </xsd:schema>"; //Create the XmlParserContext. XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None); //Implement the reader. reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context); //Add the schema. myschema.Add("xxx", new XmlTextReader(new StringReader(xsd))); //Set the schema type and add the schema to the reader. reader.ValidationType = ValidationType.Schema; reader.Schemas.Add(myschema); while (reader.Read()){Response.Write(reader.Value);} Response.Write("<br>Completed validating xmlfragment<br>"); } catch (XmlException XmlExp) { Response.Write(XmlExp.Message + "<br>"); } catch(XmlSchemaException XmlSchExp) { Response.Write(XmlSchExp.Message + "<br>"); } catch(Exception GenExp) { Response.Write(GenExp.Message + "<br>"); } finally {} XmlDocument doc; }
public void LoadAndValidate() { string path = this.GetType().Namespace + "."; Stream stm = this.GetType().Assembly.GetManifestResourceStream( path + "mixedNs.xml"); string xml = new StreamReader(stm).ReadToEnd(); XPathDocument doc = new XPathDocument(new StringReader(xml)); XPathNavigatorReader nr = new XPathNavigatorReader(doc.CreateNavigator()); XmlTextReader tr = new XmlTextReader(new StringReader(xml)); XmlValidatingReader vr = new XmlValidatingReader(tr); using (StreamReader sr = new StreamReader(this.GetType().Assembly.GetManifestResourceStream (path + "ImportedSchema1.xsd"))) { vr.Schemas.Add(XmlSchema.Read(sr, null)); } using (StreamReader sr = new StreamReader(this.GetType().Assembly.GetManifestResourceStream (path + "ImportedSchema2.xsd"))) { vr.Schemas.Add(XmlSchema.Read(sr, null)); } using (StreamReader sr = new StreamReader(this.GetType().Assembly.GetManifestResourceStream (path + "RootSchema.xsd"))) { vr.Schemas.Add(XmlSchema.Read(sr, null)); } while (vr.Read()) {} vr = new XmlValidatingReader(nr); using (StreamReader sr = new StreamReader(this.GetType().Assembly.GetManifestResourceStream (path + "ImportedSchema1.xsd"))) { vr.Schemas.Add(XmlSchema.Read(sr, null)); } using (StreamReader sr = new StreamReader(this.GetType().Assembly.GetManifestResourceStream (path + "ImportedSchema2.xsd"))) { vr.Schemas.Add(XmlSchema.Read(sr, null)); } using (StreamReader sr = new StreamReader(this.GetType().Assembly.GetManifestResourceStream (path + "RootSchema.xsd"))) { vr.Schemas.Add(XmlSchema.Read(sr, null)); } while (vr.Read()) {} Console.ReadLine(); }
public void Validate(string strXMLDoc) { try { // Declare local objects XmlTextReader tr = null; XmlSchemaCollection xsc = null; XmlValidatingReader vr = null; // Text reader object tr = new XmlTextReader(Application.StartupPath + @"\BDOCImportSchema.xsd"); xsc = new XmlSchemaCollection(); xsc.Add(null, tr); // XML validator object vr = new XmlValidatingReader(strXMLDoc, XmlNodeType.Document, null); vr.Schemas.Add(xsc); // Add validation event handler vr.ValidationType = ValidationType.Schema; vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler); // Validate XML data while (vr.Read()) ; vr.Close(); // Raise exception, if XML validation fails if (ErrorsCount > 0) { throw new Exception(ErrorMessage); } // XML Validation succeeded Console.WriteLine("XML validation succeeded.\r\n"); } catch (Exception error) { // XML Validation failed Console.WriteLine("XML validation failed." + "\r\n" + "Error Message: " + error.Message); throw new Exception("Error in XSD verification:\r\n" + error.Message); } }
private XmlReader CreateXmlReader(XmlInput forInput) { XmlReader xmlReader = forInput.CreateXmlReader(); if (xmlReader is XmlTextReader) { ((XmlTextReader) xmlReader ).WhitespaceHandling = _diffConfiguration.WhitespaceHandling; } if (_diffConfiguration.UseValidatingParser) { XmlValidatingReader validatingReader = new XmlValidatingReader(xmlReader); return validatingReader; } return xmlReader; }
public void Deserialization() { XmlFirstUpperReader fu = new XmlFirstUpperReader(Globals.GetResource( this.GetType().Namespace + ".Customer.xml")); XmlValidatingReader vr = new XmlValidatingReader(fu); vr.Schemas.Add(XmlSchema.Read(Globals.GetResource( this.GetType().Namespace + ".Customer.xsd"), null)); XmlSerializer ser = new XmlSerializer(typeof(Customer)); Customer c = (Customer) ser.Deserialize(vr); Assert.AreEqual("0736", c.Id); Assert.AreEqual("Daniel Cazzulino", c.Name); Assert.AreEqual(25, c.Order.Id); }
private static XmlReader CreateValidatingXmlReader(XmlReader reader, XmlReaderSettings settings) { #if NET_2_1 && !MONOTOUCH return(reader); #else XmlValidatingReader xvr = null; switch (settings.ValidationType) { // Auto and XDR are obsoleted in 2.0 and therefore ignored. default: return(reader); case ValidationType.DTD: xvr = new XmlValidatingReader(reader); xvr.XmlResolver = settings.XmlResolver; xvr.ValidationType = ValidationType.DTD; break; case ValidationType.Schema: return(new XmlSchemaValidatingReader(reader, settings)); } // Actually I don't think they are treated in DTD validation though... if ((settings.ValidationFlags & XmlSchemaValidationFlags.ProcessIdentityConstraints) == 0) { throw new NotImplementedException(); } //if ((settings.ValidationFlags & XmlSchemaValidationFlags.ProcessInlineSchema) != 0) // throw new NotImplementedException (); //if ((settings.ValidationFlags & XmlSchemaValidationFlags.ProcessSchemaLocation) != 0) // throw new NotImplementedException (); //if ((settings.ValidationFlags & XmlSchemaValidationFlags.ReportValidationWarnings) == 0) // throw new NotImplementedException (); return(xvr != null ? xvr : reader); #endif }
internal XmlReader AddConformanceWrapper(XmlReader baseReader) { XmlReaderSettings baseReaderSettings = baseReader.Settings; bool checkChars = false; bool noWhitespace = false; bool noComments = false; bool noPIs = false; DtdProcessing dtdProc = (DtdProcessing)(-1); bool needWrap = false; if (baseReaderSettings == null) { #pragma warning disable 618 if (_conformanceLevel != ConformanceLevel.Auto && _conformanceLevel != XmlReader.GetV1ConformanceLevel(baseReader)) { throw new InvalidOperationException(SR.Format(SR.Xml_IncompatibleConformanceLevel, _conformanceLevel.ToString())); } // get the V1 XmlTextReader ref XmlTextReader v1XmlTextReader = baseReader as XmlTextReader; if (v1XmlTextReader == null) { XmlValidatingReader vr = baseReader as XmlValidatingReader; if (vr != null) { v1XmlTextReader = (XmlTextReader)vr.Reader; } } // assume the V1 readers already do all conformance checking; // wrap only if IgnoreWhitespace, IgnoreComments, IgnoreProcessingInstructions or ProhibitDtd is true; if (_ignoreWhitespace) { WhitespaceHandling wh = WhitespaceHandling.All; // special-case our V1 readers to see if whey already filter whitespaces if (v1XmlTextReader != null) { wh = v1XmlTextReader.WhitespaceHandling; } if (wh == WhitespaceHandling.All) { noWhitespace = true; needWrap = true; } } if (_ignoreComments) { noComments = true; needWrap = true; } if (_ignorePIs) { noPIs = true; needWrap = true; } // DTD processing DtdProcessing baseDtdProcessing = DtdProcessing.Parse; if (v1XmlTextReader != null) { baseDtdProcessing = v1XmlTextReader.DtdProcessing; } if ((_dtdProcessing == DtdProcessing.Prohibit && baseDtdProcessing != DtdProcessing.Prohibit) || (_dtdProcessing == DtdProcessing.Ignore && baseDtdProcessing == DtdProcessing.Parse)) { dtdProc = _dtdProcessing; needWrap = true; } #pragma warning restore 618 } else { if (_conformanceLevel != baseReaderSettings.ConformanceLevel && _conformanceLevel != ConformanceLevel.Auto) { throw new InvalidOperationException(SR.Format(SR.Xml_IncompatibleConformanceLevel, _conformanceLevel.ToString())); } if (_checkCharacters && !baseReaderSettings.CheckCharacters) { checkChars = true; needWrap = true; } if (_ignoreWhitespace && !baseReaderSettings.IgnoreWhitespace) { noWhitespace = true; needWrap = true; } if (_ignoreComments && !baseReaderSettings.IgnoreComments) { noComments = true; needWrap = true; } if (_ignorePIs && !baseReaderSettings.IgnoreProcessingInstructions) { noPIs = true; needWrap = true; } if ((_dtdProcessing == DtdProcessing.Prohibit && baseReaderSettings.DtdProcessing != DtdProcessing.Prohibit) || (_dtdProcessing == DtdProcessing.Ignore && baseReaderSettings.DtdProcessing == DtdProcessing.Parse)) { dtdProc = _dtdProcessing; needWrap = true; } } if (needWrap) { IXmlNamespaceResolver readerAsNSResolver = baseReader as IXmlNamespaceResolver; if (readerAsNSResolver != null) { return(new XmlCharCheckingReaderWithNS(baseReader, readerAsNSResolver, checkChars, noWhitespace, noComments, noPIs, dtdProc)); } else { return(new XmlCharCheckingReader(baseReader, checkChars, noWhitespace, noComments, noPIs, dtdProc)); } } else { return(baseReader); } }
internal XmlReader AddConformanceWrapper(XmlReader baseReader) { XmlReaderSettings settings = baseReader.Settings; bool checkCharacters = false; bool ignoreWhitespace = false; bool ignoreComments = false; bool ignorePis = false; System.Xml.DtdProcessing dtdProcessing = ~System.Xml.DtdProcessing.Prohibit; bool flag5 = false; if (settings == null) { if ((this.conformanceLevel != System.Xml.ConformanceLevel.Auto) && (this.conformanceLevel != XmlReader.GetV1ConformanceLevel(baseReader))) { throw new InvalidOperationException(Res.GetString("Xml_IncompatibleConformanceLevel", new object[] { this.conformanceLevel.ToString() })); } XmlTextReader reader = baseReader as XmlTextReader; if (reader == null) { XmlValidatingReader reader2 = baseReader as XmlValidatingReader; if (reader2 != null) { reader = (XmlTextReader)reader2.Reader; } } if (this.ignoreWhitespace) { WhitespaceHandling all = WhitespaceHandling.All; if (reader != null) { all = reader.WhitespaceHandling; } if (all == WhitespaceHandling.All) { ignoreWhitespace = true; flag5 = true; } } if (this.ignoreComments) { ignoreComments = true; flag5 = true; } if (this.ignorePIs) { ignorePis = true; flag5 = true; } System.Xml.DtdProcessing parse = System.Xml.DtdProcessing.Parse; if (reader != null) { parse = reader.DtdProcessing; } if (((this.dtdProcessing == System.Xml.DtdProcessing.Prohibit) && (parse != System.Xml.DtdProcessing.Prohibit)) || ((this.dtdProcessing == System.Xml.DtdProcessing.Ignore) && (parse == System.Xml.DtdProcessing.Parse))) { dtdProcessing = this.dtdProcessing; flag5 = true; } } else { if ((this.conformanceLevel != settings.ConformanceLevel) && (this.conformanceLevel != System.Xml.ConformanceLevel.Auto)) { throw new InvalidOperationException(Res.GetString("Xml_IncompatibleConformanceLevel", new object[] { this.conformanceLevel.ToString() })); } if (this.checkCharacters && !settings.CheckCharacters) { checkCharacters = true; flag5 = true; } if (this.ignoreWhitespace && !settings.IgnoreWhitespace) { ignoreWhitespace = true; flag5 = true; } if (this.ignoreComments && !settings.IgnoreComments) { ignoreComments = true; flag5 = true; } if (this.ignorePIs && !settings.IgnoreProcessingInstructions) { ignorePis = true; flag5 = true; } if (((this.dtdProcessing == System.Xml.DtdProcessing.Prohibit) && (settings.DtdProcessing != System.Xml.DtdProcessing.Prohibit)) || ((this.dtdProcessing == System.Xml.DtdProcessing.Ignore) && (settings.DtdProcessing == System.Xml.DtdProcessing.Parse))) { dtdProcessing = this.dtdProcessing; flag5 = true; } } if (!flag5) { return(baseReader); } IXmlNamespaceResolver readerAsNSResolver = baseReader as IXmlNamespaceResolver; if (readerAsNSResolver != null) { return(new XmlCharCheckingReaderWithNS(baseReader, readerAsNSResolver, checkCharacters, ignoreWhitespace, ignoreComments, ignorePis, dtdProcessing)); } return(new XmlCharCheckingReader(baseReader, checkCharacters, ignoreWhitespace, ignoreComments, ignorePis, dtdProcessing)); }
internal XmlReader AddConformanceWrapper(XmlReader baseReader) { XmlReaderSettings baseReaderSettings = baseReader.Settings; bool checkChars = false; bool noWhitespace = false; bool noComments = false; bool noPIs = false; DtdProcessing dtdProc = (DtdProcessing)(-1); bool needWrap = false; if (baseReaderSettings == null) { #pragma warning disable 618 #if SILVERLIGHT // Starting from Windows phone 8.1 (TargetsAtLeast_Desktop_V4_5_1) we converge with the desktop behavior so we'll let the reader // not throw exception if has different conformance level than Auto. if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5_1) { if (this.conformanceLevel != ConformanceLevel.Auto && this.conformanceLevel != XmlReader.GetV1ConformanceLevel(baseReader)) { throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString())); } } else if (this.conformanceLevel != ConformanceLevel.Auto) { throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString())); } #else if (this.conformanceLevel != ConformanceLevel.Auto && this.conformanceLevel != XmlReader.GetV1ConformanceLevel(baseReader)) { throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString())); } #endif #if !SILVERLIGHT // get the V1 XmlTextReader ref XmlTextReader v1XmlTextReader = baseReader as XmlTextReader; if (v1XmlTextReader == null) { XmlValidatingReader vr = baseReader as XmlValidatingReader; if (vr != null) { v1XmlTextReader = (XmlTextReader)vr.Reader; } } #endif // assume the V1 readers already do all conformance checking; // wrap only if IgnoreWhitespace, IgnoreComments, IgnoreProcessingInstructions or ProhibitDtd is true; if (this.ignoreWhitespace) { WhitespaceHandling wh = WhitespaceHandling.All; #if !SILVERLIGHT // special-case our V1 readers to see if whey already filter whitespaces if (v1XmlTextReader != null) { wh = v1XmlTextReader.WhitespaceHandling; } #endif if (wh == WhitespaceHandling.All) { noWhitespace = true; needWrap = true; } } if (this.ignoreComments) { noComments = true; needWrap = true; } if (this.ignorePIs) { noPIs = true; needWrap = true; } // DTD processing DtdProcessing baseDtdProcessing = DtdProcessing.Parse; #if !SILVERLIGHT if (v1XmlTextReader != null) { baseDtdProcessing = v1XmlTextReader.DtdProcessing; } #endif if ((this.dtdProcessing == DtdProcessing.Prohibit && baseDtdProcessing != DtdProcessing.Prohibit) || (this.dtdProcessing == DtdProcessing.Ignore && baseDtdProcessing == DtdProcessing.Parse)) { dtdProc = this.dtdProcessing; needWrap = true; } #pragma warning restore 618 } else { if (this.conformanceLevel != baseReaderSettings.ConformanceLevel && this.conformanceLevel != ConformanceLevel.Auto) { throw new InvalidOperationException(Res.GetString(Res.Xml_IncompatibleConformanceLevel, this.conformanceLevel.ToString())); } if (this.checkCharacters && !baseReaderSettings.CheckCharacters) { checkChars = true; needWrap = true; } if (this.ignoreWhitespace && !baseReaderSettings.IgnoreWhitespace) { noWhitespace = true; needWrap = true; } if (this.ignoreComments && !baseReaderSettings.IgnoreComments) { noComments = true; needWrap = true; } if (this.ignorePIs && !baseReaderSettings.IgnoreProcessingInstructions) { noPIs = true; needWrap = true; } if ((this.dtdProcessing == DtdProcessing.Prohibit && baseReaderSettings.DtdProcessing != DtdProcessing.Prohibit) || (this.dtdProcessing == DtdProcessing.Ignore && baseReaderSettings.DtdProcessing == DtdProcessing.Parse)) { dtdProc = this.dtdProcessing; needWrap = true; } } if (needWrap) { IXmlNamespaceResolver readerAsNSResolver = baseReader as IXmlNamespaceResolver; if (readerAsNSResolver != null) { return(new XmlCharCheckingReaderWithNS(baseReader, readerAsNSResolver, checkChars, noWhitespace, noComments, noPIs, dtdProc)); } else { return(new XmlCharCheckingReader(baseReader, checkChars, noWhitespace, noComments, noPIs, dtdProc)); } } else { return(baseReader); } }
private void LoadDocumentType(XmlValidatingReader vr, XmlDocumentType dtNode) { SchemaInfo schInfo = vr.GetSchemaInfo(); if (schInfo != null) { //set the schema information into the document doc.SchemaInformation = schInfo; // Notation hashtable if (schInfo.Notations != null) { foreach (SchemaNotation scNot in schInfo.Notations.Values) { dtNode.Notations.SetNamedItem(new XmlNotation(scNot.Name.Name, scNot.Pubid, scNot.SystemLiteral, doc)); } } // Entity hashtables if (schInfo.GeneralEntities != null) { foreach (SchemaEntity scEnt in schInfo.GeneralEntities.Values) { XmlEntity ent = new XmlEntity(scEnt.Name.Name, scEnt.Text, scEnt.Pubid, scEnt.Url, scEnt.NData.IsEmpty ? null : scEnt.NData.Name, doc); ent.SetBaseURI(scEnt.DeclaredURI); dtNode.Entities.SetNamedItem(ent); } } if (schInfo.ParameterEntities != null) { foreach (SchemaEntity scEnt in schInfo.ParameterEntities.Values) { XmlEntity ent = new XmlEntity(scEnt.Name.Name, scEnt.Text, scEnt.Pubid, scEnt.Url, scEnt.NData.IsEmpty ? null : scEnt.NData.Name, doc); ent.SetBaseURI(scEnt.DeclaredURI); dtNode.Entities.SetNamedItem(ent); } } doc.Entities = dtNode.Entities; //extract the elements which has attribute defined as ID from the element declarations IDictionaryEnumerator elementDecls = schInfo.ElementDecls.GetEnumerator(); if (elementDecls != null) { elementDecls.Reset(); while (elementDecls.MoveNext()) { SchemaElementDecl elementDecl = (SchemaElementDecl)elementDecls.Value; if (elementDecl.AttDefs != null) { IDictionaryEnumerator attDefs = elementDecl.AttDefs.GetEnumerator(); while (attDefs.MoveNext()) { SchemaAttDef attdef = (SchemaAttDef)attDefs.Value; if (attdef.Datatype.TokenizedType == XmlTokenizedType.ID) { doc.AddIdInfo( doc.GetXmlName(elementDecl.Name.Name, elementDecl.Name.Namespace), doc.GetXmlName(attdef.Name.Name, attdef.Name.Namespace)); break; } } } } } } }