当前位置: 首页>>代码示例>>C#>>正文


C# Xml.XmlValidatingReader类代码示例

本文整理汇总了C#中System.Xml.XmlValidatingReader的典型用法代码示例。如果您正苦于以下问题:C# XmlValidatingReader类的具体用法?C# XmlValidatingReader怎么用?C# XmlValidatingReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


XmlValidatingReader类属于System.Xml命名空间,在下文中一共展示了XmlValidatingReader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CreateAndCacheDocument

 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;
 }
开发者ID:zanyants,项目名称:mvp.xml,代码行数:26,代码来源:XPointerReader.cs

示例2: 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

示例3: 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

示例4: 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

示例5: 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

示例6: 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

示例7: 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

示例8: XIncludingReader

        /// <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;		
        }
开发者ID:zanyants,项目名称:mvp.xml,代码行数:36,代码来源:XIncludingReader.cs

示例9: Read

 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;
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:30,代码来源:WebReferenceOptions.cs

示例10: 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

示例11: GReader

        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);
            }
        }
开发者ID:simas76,项目名称:scielo-dev,代码行数:29,代码来源:GReader.cs

示例12: Parse

        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;
            }
        }
开发者ID:slluis,项目名称:monodevelop-prehistoric,代码行数:60,代码来源:HighlightingDefinitionParser.cs

示例13: 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

示例14: NamespaceMapper

		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();
		}
开发者ID:tgassner,项目名称:NDoc,代码行数:32,代码来源:NamespaceMapper.cs

示例15: 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


注:本文中的System.Xml.XmlValidatingReader类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。