Exemple #1
0
        private void InternalValidationEventHandler(object sender, ValidationEventArgs e)
        {
            if (e.Severity != XmlSeverityType.Error)
            {
                return;
            }

            var index = ((XmlReader)sender).NodeType == XmlNodeType.EndElement ? _indicesStack.Peek() : _validationIndex;

            var location = LocationMap[index];

            ValidationErrorEvent?.Invoke(CompilerErrorFactory.XmlSchemaValidationError(e.Exception, location));
        }
        public void ValidateGeneratedFile(string fileName)
        {
            try
            {
                var settings = new XmlReaderSettings
                {
                    ConformanceLevel = ConformanceLevel.Document,
                    ValidationFlags  = XmlSchemaValidationFlags.AllowXmlAttributes |
                                       XmlSchemaValidationFlags.ReportValidationWarnings,
                    Schemas = XmlSchemaSet
                };

                if (XmlSchemaSet.Count > 0)
                {
                    settings.ValidationType = ValidationType.Schema;
                }

                _validationIndex = 0;
                _indicesStack    = new Stack <int>();
                _indicesStack.Push(0);
                settings.ValidationEventHandler += InternalValidationEventHandler;

                using (var textReader = new XmlTextReader(fileName))
                {
                    using (var reader = XmlReader.Create(textReader, settings))
                    {
                        while (reader.Read())
                        {
                            if (reader.NodeType == XmlNodeType.Element)
                            {
                                if (!reader.IsEmptyElement)
                                {
                                    _indicesStack.Push(_validationIndex); //This stack is used to store index of the current parent element.
                                }
                                _validationIndex++;
                                _validationIndex += GetAttributesCount(reader);
                            }

                            if (reader.NodeType == XmlNodeType.EndElement)
                            {
                                _indicesStack.Pop();
                            }
                        }
                    }
                }
            }
            catch (XmlSchemaValidationException ex)
            {
                ValidationErrorEvent?.Invoke(CompilerErrorFactory.XmlSchemaValidationError(ex));
            }
        }