Read() публичный Метод

public Read ( ) : bool
Результат bool
		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) {
			}
		}
Пример #2
0
        /// <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);
            }
        }
Пример #3
0
        /// <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;
        }
Пример #4
0
        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());
        }
Пример #5
0
        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);
        }
        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();
        }
Пример #7
0
Файл: test.cs Проект: mono/gert
	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 ();
		}
	}
Пример #8
0
        /*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";
            }
        }
		public void TestEmptySchema ()
		{
			string xml = "<root/>";
			xvr = PrepareXmlReader (xml);
			xvr.ValidationType = ValidationType.Schema;
			xvr.Read ();	// Is is missing schema component.
		}
Пример #10
0
        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()) {}
        }
Пример #11
0
        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 static void Validate(XmlReader reader)
        {
            XmlValidatingReader vr = new XmlValidatingReader(reader);

            vr.ValidationType = ValidationType.Auto;
            vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);

            while (vr.Read()){};
        }
Пример #13
0
        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);
        }
Пример #14
0
        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();
        }
Пример #15
0
        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();
        */
        }
Пример #16
0
        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;
        }
Пример #17
0
		public void TestElementContent ()
		{
			string intSubset = "<!ELEMENT root (foo)><!ELEMENT foo EMPTY>";
			string dtd = "<!DOCTYPE root [" + intSubset + "]>";
			string xml = dtd + "<root />";
			dvr = PrepareXmlReader (xml);
			dvr.Read ();	// DTD
			try {
				dvr.Read ();	// root: invalid end
				Assert.Fail ("should be failed.");
			} catch (XmlSchemaException) {
			}

			xml = dtd + "<root>Test.</root>";
			dvr = PrepareXmlReader (xml);
			dvr.Read ();	// DTD
			dvr.Read ();	// root
			try {
				dvr.Read ();	// invalid end
				Assert.Fail ("should be failed.");
			} catch (XmlSchemaException) {
			}

			xml = dtd + "<root><foo /></root>";
			dvr = PrepareXmlReader (xml);
			dvr.Read ();	// DTD
			dvr.Read ();	// root
			dvr.Read ();	// foo

			xml = dtd + "<root><bar /></root>";
			dvr = PrepareXmlReader (xml);
			dvr.Read ();	// DTD
			dvr.Read ();	// root
			try {
				dvr.Read ();	// invalid element
				Assert.Fail ("should be failed.");
			} catch (XmlSchemaException) {
			}
		}
Пример #18
0
		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();
		}
Пример #19
0
		public void TestSingleElement ()
		{
			string intSubset = "<!ELEMENT root EMPTY>";
			string dtd = "<!DOCTYPE root [" + intSubset + "]>";
			string xml = dtd + "<root />";
			dvr = PrepareXmlReader (xml);
			dvr.Read ();	// DTD
			dvr.Read ();

			xml = dtd + "<invalid />";
			dvr = PrepareXmlReader (xml);
			dvr.Read ();	// DTD
			try {
				dvr.Read ();	// invalid element.
				Assert.Fail ("should be failed.");
			} catch (XmlSchemaException) {
			}

			xml = dtd + "<root>invalid PCDATA.</root>";
			dvr = PrepareXmlReader (xml);
			dvr.Read ();	// DTD
			dvr.Read ();	// root
			try {
				dvr.Read ();	// invalid text
				Assert.Fail ("should be failed.");
			} catch (XmlSchemaException) {
			}

			xml = dtd + "<root><invalid_child /></root>";
			dvr = PrepareXmlReader (xml);
			dvr.Read ();	// DTD
			dvr.Read ();	// root
			try {
				dvr.Read ();	// invalid child
				Assert.Fail ("should be failed.");
			} catch (XmlSchemaException) {
			}
		}
Пример #20
0
        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);
            }
        }
Пример #21
0
        /// <summary>
        /// Validates the specified xml content
        /// </summary>
        /// <param name="sImportDocument">Xml content to validate</param>
        /// <returns>Error messages if any, else "true"</returns>
        public List<string> ValidateCrmImportDocument(string sImportDocument)
        {
            ValidationEventHandler eventHandler = ShowCompileErrors;
            XmlSchemaCollection myschemacoll = new XmlSchemaCollection();
            XmlValidatingReader vr;

            try
            {
                using (StreamReader schemaReader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("MsCrmTools.SiteMapEditor.Resources.sitemap.xsd")))
                {
                    //Load the XmlValidatingReader.
                    vr = new XmlValidatingReader(schemaReader.BaseStream, XmlNodeType.Element, null);

                    vr.Schemas.Add(myschemacoll);
                    vr.ValidationType = ValidationType.Schema;

                    while (vr.Read())
                    {
                    }
                }

                return messages;
            }
            //This code catches any XML exceptions.
            catch (XmlException XmlExp)
            {
                messages.Add(XmlExp.Message);
                return messages;
            }
            //This code catches any XML schema exceptions.
            catch (XmlSchemaException XmlSchemaExp)
            {
                messages.Add(XmlSchemaExp.Message);
                return messages;
            }
            //This code catches any standard exceptions.
            catch (Exception GeneralExp)
            {
                messages.Add(GeneralExp.Message);
                return messages;
            }
            finally
            {
                vr = null;
                myschemacoll = null;
            }
        }
Пример #22
0
		static void ValidateFile (string file)
		{
			IsValid = true;
			try {
				reader = new XmlValidatingReader (new XmlTextReader (file));
				reader.ValidationType = ValidationType.Schema;
				reader.Schemas.Add (schema);
				reader.ValidationEventHandler += new ValidationEventHandler (OnValidationEvent);
				while (reader.Read ()) {
					// do nothing
				}
				reader.Close ();
			}
			catch (Exception e) {
				Console.WriteLine ("mdvalidator: error: " + e.ToString ());
			}
		}
Пример #23
0
 public static void ValidateXml(Stream xmlStream, XmlSchema xsdSchema)
 {
     XmlTextReader reader1 = null;
       try
       {
     reader1 = new XmlTextReader(xmlStream);
     XmlSchemaCollection collection1 = new XmlSchemaCollection();
     collection1.Add(xsdSchema);
     XmlValidatingReader reader2 = new XmlValidatingReader(reader1);
     reader2.ValidationType = ValidationType.Schema;
     reader2.Schemas.Add(collection1);
     ArrayList list1 = new ArrayList();
     while (reader2.ReadState != ReadState.EndOfFile)
     {
       try
       {
     reader2.Read();
     continue;
       }
       catch (XmlSchemaException exception1)
       {
     list1.Add(exception1);
     continue;
       }
     }
     if (list1.Count != 0)
     {
       throw new XmlValidationException(list1);
     }
       }
       catch (XmlValidationException exception2)
       {
     throw exception2;
       }
       catch (Exception exception3)
       {
     throw new XmlValidationException(exception3.Message, exception3);
       }
       finally
       {
     if (reader1 != null)
     {
       reader1.Close();
     }
       }
 }
Пример #24
0
        private void ValidXml()
        {
            XmlTextReader tr = new XmlTextReader("HeadCount.xml");
            XmlValidatingReader vr = new XmlValidatingReader(tr);
            // XmlReader xr =
            vr.ValidationType = ValidationType.Schema;
            vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);

            while (vr.Read())
            {
                //    PrintTypeInfo(vr);
                if (vr.NodeType == XmlNodeType.Element)
                {
                    // while (vr.MoveToNextAttribute())
                    //     PrintTypeInfo(vr);
                }
            }
            //    Console.WriteLine("Validation finished");
        }
Пример #25
0
        // XmlReaderSample5/form.cs
        protected void button1_Click(object sender, System.EventArgs e)
        {
            //change this to match your path structure.
            string fileName = "..\\booksVal.xml";
            XmlTextReader tr=new XmlTextReader(fileName);
            XmlValidatingReader trv=new XmlValidatingReader(tr);

            //Set validation type
            trv.ValidationType=ValidationType.XDR;
            //Add in the Validation eventhandler
            trv.ValidationEventHandler +=
                new ValidationEventHandler(this.ValidationEvent);
            //Read in node at a time
            while(trv.Read())
            {
                if(trv.NodeType == XmlNodeType.Text)
                    listBox1.Items.Add(trv.Value);
            }
        }
Пример #26
0
        public bool ValidateXMLFile()
        {
            XmlTextReader objXmlTextReader =null;
            XmlValidatingReader objXmlValidatingReader=null ;

            try
            {
                //creating a text reader for the XML file already picked by the
                //overloaded constructor above viz..clsSchemaValidator
                objXmlTextReader = new XmlTextReader(m_sXMLFileName);
                //creating a validating reader for that objXmlTextReader just created
                objXmlValidatingReader = new XmlValidatingReader (objXmlTextReader);
                //For validation we are adding the schema collection in
                //ValidatingReaders Schema collection.
                objXmlValidatingReader.Schemas.Add (m_objXmlSchemaCollection);
                //Attaching the event handler now in case of failures
                objXmlValidatingReader.ValidationEventHandler += new ValidationEventHandler
                    (ValidationFailed);
                //Actually validating the data in the XML file with a empty while.
                //which would fire the event ValidationEventHandler and invoke
                //our ValidationFailed function
                while (objXmlValidatingReader.Read())
                {
                }
                //Note:- If any issue is faced in the above while it will invoke ValidationFailed
                //which will in turn set the module level m_bIsFailure boolean variable to false
                //thus returning true as a signal to the calling function that the ValidateXMLFile
                //function(this function) has encountered failure
                return m_bIsFailure;
            }
            catch (Exception ex)
            {
                MessageBox.Show ("Exception : " + ex.Message);
                return true;
            }
            finally
            {
                // close the readers, no matter what.
                objXmlValidatingReader.Close ();
                objXmlTextReader.Close ();
            }
        }
Пример #27
0
    /* Takes a type name, and a valid example of that type, 
       Creates a schema consisting of a single element of that
       type, and validates a bit of xml containing the valid 
       value, with whitespace against that schema.
     
FIXME: Really we want to test the value of whitespace more
       directly that by creating a schema then parsing a string.
     
     */

    public void WhiteSpaceTest(string type, string valid) {
      passed = true;
      XmlSchema schema = new XmlSchema();

      schema.TargetNamespace= "http://example.com/testCase";
      XmlSchemaElement element = new XmlSchemaElement();
      element.Name = "a";
      element.SchemaTypeName = new XmlQualifiedName(type, "http://www.w3.org/2001/XMLSchema");
      schema.Items.Add(element);
      schema.Compile(new ValidationEventHandler(ValidationCallbackOne));

      XmlValidatingReader vr = new XmlValidatingReader(new XmlTextReader(new StringReader("<a xmlns='http://example.com/testCase'>\n\n"+valid+"\n\n</a>" )));
      vr.Schemas.Add(schema);
      vr.ValidationType = ValidationType.Schema;
//      vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne);
      while(vr.Read()) { };
      vr.Close();
      
      Assert(type + " doesn't collapse whitespace: " + (errorInfo != null ? errorInfo.Message : null), passed);
    }
Пример #28
0
        public bool validateXml(String infile)
        {
            //First we create the xmltextreader
            XmlTextReader xmlr = new XmlTextReader(infile);
            //We pass the xmltextreader into the xmlvalidatingreader
            //'This will validate the xml doc with the schema file
            //'NOTE the xml file it self points to the schema file
            XmlValidatingReader xmlvread = new XmlValidatingReader(xmlr);
            //
            //      //                      ' Set the validation event handler
            xmlvread.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
            m_Success = true; //'make sure to reset the success var
            //
            //      //' Read XML data
            while (xmlvread.Read()) { }

            //'Close the reader.
            xmlvread.Close();

            //'The validationeventhandler is the only thing that would set m_Success to false
            return m_Success;
        }
Пример #29
0
        private bool validateCommon()
        {
            bool success=true;
              //d_nrMessages=0;
              try {
              XmlValidatingReader vr = new XmlValidatingReader(d_xtr);

              vr.ValidationType = ValidationType.Schema;
              vr.ValidationEventHandler += new ValidationEventHandler (validationHandler);

              // consume
              while(vr.Read())
            ;
              } catch(Exception e) {
            success=false;
            if (d_throwErrors)
              throw e;
              } finally {
            d_xtr.Close();
              }
              return success;
        }
Пример #30
0
 static void Main(string[] args)
 {
     //
     // TODO: Add code to start application here
     //
     try
     {
         if(args.Length!=1)
         {
             System.Console.WriteLine("Usage: xsd.exe source-uri");
             return;
         }
         SX.XmlTextReader reader = new SX.XmlTextReader(args[0]);
         SX.XmlValidatingReader validatingReader =
             new SX.XmlValidatingReader(reader);
         while(validatingReader.Read());
     }
     catch(System.Exception e)
     {
         System.Console.WriteLine(e.ToString());
     }
 }
Пример #31
0
        private static bool isValid = true; // If a validation error occurs,
                                            // set this flag to false in the
                                            // validation event handler. 
        static void Main(string[] args)
        {
            XmlTextReader r = new XmlTextReader(@"..\..\GenKeyIDList.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.
                Console.WriteLine(v.LocalName);

                if (v.LocalName == "GenericKeyIDList")
                {
                    if(v.IsStartElement())
                    {
                        v.MoveToFirstAttribute();               
                        v.ReadAttributeValue();
                        Console.WriteLine("    " + v.ReadContentAsString());
                    }
                }
            }
            v.Close();

            // Check whether the document is valid or invalid.
            if (isValid)
            {
               Console.WriteLine("Document is valid");
            }
            else
            {
               Console.WriteLine("Document is invalid");
            }

        
        }