當前位置: 首頁>>代碼示例>>C#>>正文


C# XmlValidatingReader.Read方法代碼示例

本文整理匯總了C#中System.Xml.XmlValidatingReader.Read方法的典型用法代碼示例。如果您正苦於以下問題:C# XmlValidatingReader.Read方法的具體用法?C# XmlValidatingReader.Read怎麽用?C# XmlValidatingReader.Read使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在System.Xml.XmlValidatingReader的用法示例。


在下文中一共展示了XmlValidatingReader.Read方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: TestSimpleValidation

		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) {
			}
		}
開發者ID:calumjiao,項目名稱:Mono-Class-Libraries,代碼行數:32,代碼來源:XsdValidatingReaderTests.cs

示例2: Page_Load

        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();
        }
開發者ID:sujithkumar640,項目名稱:Technical-Concepts,代碼行數:29,代碼來源:WebForm1.aspx.cs

示例3: IsValidXML

        /// <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;
        }
開發者ID:CaiqueDourado,項目名稱:mailee-api-dotnet,代碼行數:30,代碼來源:Util.cs

示例4: ValidaSchema

        /// <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);
            }
        }
開發者ID:njmube,項目名稱:NFeEletronica.NET,代碼行數:41,代碼來源:Xml.cs

示例5: ParseItemsConfiguration

        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;
        }
開發者ID:wshanshan,項目名稱:DDD,代碼行數:32,代碼來源:ItemParser.cs

示例6: Main

	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 ();
		}
	}
開發者ID:mono,項目名稱:gert,代碼行數:26,代碼來源:test.cs

示例7: ValidateSchema

        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());
        }
開發者ID:krobertson,項目名稱:hopsharp,代碼行數:25,代碼來源:HoptoadValidator.cs

示例8: Validar

        /*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";
            }
        }
開發者ID:Servtes,項目名稱:XMLnator,代碼行數:31,代碼來源:ValidarXml.cs

示例9: TestEmptySchema

		public void TestEmptySchema ()
		{
			string xml = "<root/>";
			xvr = PrepareXmlReader (xml);
			xvr.ValidationType = ValidationType.Schema;
			xvr.Read ();	// Is is missing schema component.
		}
開發者ID:calumjiao,項目名稱:Mono-Class-Libraries,代碼行數:7,代碼來源:XsdValidatingReaderTests.cs

示例10: ShouldGenerateASchemaToValidateTestSubClassXml

        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()) {}
        }
開發者ID:dtewinkel,項目名稱:NetReflector,代碼行數:25,代碼來源:XsdGeneratorTest.cs

示例11: BaseCodeGenerator

        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);
        }
開發者ID:killbug2004,項目名稱:WSProf,代碼行數:29,代碼來源:BaseCodeGenerator.cs

示例12: Validate

        public static void Validate(XmlReader reader)
        {
            XmlValidatingReader vr = new XmlValidatingReader(reader);

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

            while (vr.Read()){};
        }
開發者ID:BackupTheBerlios,項目名稱:ferdadataminer-svn,代碼行數:9,代碼來源:GraphMLSerializer.cs

示例13: Main

        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();
        }
開發者ID:GerhardMaier,項目名稱:COLLADA-CTS,代碼行數:55,代碼來源:SchemaValidate.cs

示例14: Main

        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();
        */
        }
開發者ID:ehershey,項目名稱:development,代碼行數:54,代碼來源:Program.cs

示例15: Page_Load

        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;
        }
開發者ID:rags,項目名稱:playground,代碼行數:52,代碼來源:frmValidatingReader.aspx.cs


注:本文中的System.Xml.XmlValidatingReader.Read方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。