Validate() public method

public Validate ( ValidationEventHandler validationEventHandler ) : void
validationEventHandler ValidationEventHandler
return void
        internal static void Main()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("../../../correctXML.xml");
            doc.Schemas.Add("urn:catalogueSchema", "../../../catalogueSchema.xsd");

            ValidationEventHandler eventhandler = new ValidationEventHandler(ValidateEventHandler);
            doc.Validate(eventhandler);

            // I Just delete albums element.
            doc.Load("../../../invalidXML.xml");
            doc.Validate(eventhandler);
        }
Example #2
0
        /// <summary>
        /// ¬озвращает список клиентов прочитанный из указанного XML файла с помощью класса XmlDocument
        /// </summary>
        /// <param name="customersXmlPath">ѕуть к файлу customers.xml</param>
        /// <param name="customersXsdPath">ѕуть к файлу customers.xsd</param>
        /// <returns>Cписок клиентов</returns>
        /// <remarks>ќбратите внимание, что мы всегда возврашаем коллекцию даже если ничего не прочитали из файла</remarks>
        /// <exception cref="InvalidCustomerFileException">¬ходной файл не соответствует XML схеме</exception>
        public static List<Customer> GetCustomersUsingXmlDocument(string customersXmlPath, string customersXsdPath = null)
        {
            var customers = new List<Customer>();

            var xmlDoc = new XmlDocument();
            xmlDoc.Load(customersXmlPath);
            if (customersXsdPath != null)
            {
                xmlDoc.Schemas.Add(CUSTOMERS_NAMESPACE, customersXsdPath);

                try
                {
                    xmlDoc.Validate(null);
                }
                catch (XmlSchemaValidationException ex)
                {
                    throw new InvalidCustomerFileException("Customer.xml has some errors", ex);
                }
            }

            var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
            nsmgr.AddNamespace("c", CUSTOMERS_NAMESPACE);

            XmlNodeList customerNodes = xmlDoc.DocumentElement.SelectNodes("c:Customer", nsmgr);
            foreach (XmlElement customerElement in customerNodes)
            {
                customers.Add(CreateCustomerFromXmlElement(customerElement, nsmgr));
            }

            return customers;
        }
Example #3
0
        private XmlDocument ReadXml(string file) {
            TextReader xml = new StreamReader(file);
            XmlReader xsd = XmlReader.Create(new StreamReader("HVP_Transaction.xsd"));

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Schemas.Add(null, xsd);
            settings.ValidationType = ValidationType.Schema;
            settings.ValidationEventHandler += new ValidationEventHandler(validationEventHandler);

            XmlReader reader = XmlReader.Create(xml, settings);
            XmlDocument document = new XmlDocument();

            valid = true;
            try
            {
                document.Load(reader);
                document.Validate(new ValidationEventHandler(validationEventHandler));
            }
            finally
            {
                reader.Close();
                xml.Close();
                xsd.Close();
                
            }

            return valid ? document : null;
        }
Example #4
0
 public static bool Validate(XmlDocument document, XmlSchema schema)
 {
     succes = true;
     document.Schemas.Add(schema);
     document.Validate(new ValidationEventHandler(ValidationCallBack));
     return succes;
 }
Example #5
0
        public Boolean Validate()
        {
            XmlTextReader txtreader = null;
            try
            {
                txtreader = new XmlTextReader(fileName);

                XmlDocument doc = new XmlDocument();
                doc.Load(txtreader);
                ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);

                doc.Validate(eventHandler);
            }
            catch (IOException e)
            {
                LogBookController.Instance.addLogLine("Error accessing chapter files. Probably doesn't exist. \n" + e, LogMessageCategories.Error);
               
                return false;
            }
            catch (XmlException e)
            {
                LogBookController.Instance.addLogLine("Error inside chapters XML file, trying again.\n" + e, LogMessageCategories.Error);
                return false;
            }
            finally
            {
                txtreader.Close();
            }

            return true;
        }
        public Domain.ErrorCode Validate(IXPathNavigable configSectionNode)
        {
            log.Debug("Validating the configuration");

            lock (syncLock)
            {
                try
                {
                    isValid = true;

                    //TODO: is there a better way to do this?
                    var navigator = configSectionNode.CreateNavigator();
                    var doc = new XmlDocument();
                    doc.LoadXml(navigator.OuterXml);
                    doc.Schemas.Add(Schema);
                    doc.Validate(ValidationCallback);

                    if (isValid)
                    {
                        log.Debug("The configuration is valid");
                    }
                    else
                    {
                        log.Error("The configuration is invalid");
                    }
                }
                catch (XmlException ex)
                {
                    log.Error("An error occurred when validating the configuration", ex);
                    isValid = false;
                }

                return isValid ? Domain.ErrorCode.Ok : Domain.ErrorCode.InvalidConfig;
            }
        }
Example #7
0
        /// <summary>
        /// 	Valida uno stream XML dal tuo schema XSD
        /// </summary>
        /// <param name = "avviso"></param>
        /// <param name = "fileStream">Stream XML</param>
        /// <param name = "xsdFilePath">Schema XSD</param>
        /// <returns></returns>
        public static bool ValidaXml(out string avviso, Stream fileStream, string xsdFilePath)
        {
            _xmlValido = true;

            using (fileStream)
            {
                try
                {
                    var document = new XmlDocument();
                    document.PreserveWhitespace = true;
                    document.Schemas.Add(null, xsdFilePath);
                    document.Load(fileStream);
                    document.Validate(ValidationCallBack);
                }
                catch (Exception ex)
                {
                    avviso = ex.Message;
                    _xmlValido = false;
                    return _xmlValido;
                }

                avviso = _avviso;
                return _xmlValido;
            }
        }
Example #8
0
        /// <summary>
        /// Initializes the mission and vilidates the mission file with mission XMLSchema file.
        /// </summary>
        /// <param name="missionFilePath">The path to the file with mission.</param>
        /// <param name="teams">The dictionary which will be filled by Teams (should be empty).</param>
        /// <param name="solarSystems">The dictionary which will be filled by SolarSystem. (should be empty).</param>
        public XmlLoader(string missionFilePath, Dictionary<string, Team> teams,
			List<SolarSystem> solarSystems)
        {
            loadedMovements = new Dictionary<string, string>();
            loadedOccupations = new List<Tuple<List<string>, string, int>>();
            loadedFights = new List<Tuple<List<string>, List<string>>>();
            teamRealationDict = new Dictionary<Team, List<Team>>();

            this.teamDict = teams;
            this.solarSystemList = solarSystems;
            xml = new XmlDocument();

            // Checks the mission XmlSchema
            XmlSchemaSet schemas = new XmlSchemaSet();
            schemas.Add("", schemaPath);

            xml.Load(missionFilePath);
            xml.Schemas.Add(schemas);
            string msg = "";
            xml.Validate((o, err) => {
                msg = err.Message;
            });

            if (msg == "") {
                Console.WriteLine("Document is valid");
            } else {
                throw new XmlLoadException("Document invalid: " + msg);
            }
            root = xml.DocumentElement;

            runtimeCtor = new RunTimeCreator();
        }
 /// <summary>
 /// Validate gbxml file against the 6.01 schema XSD
 /// </summary>
 private void ValidategbXML_601()
 {
     XmlDocument xml = new XmlDocument();
     xml.Load(@"data/TestgbXML.xml");
     xml.Schemas.Add(null, @"data/GreenBuildingXML_Ver6.01.xsd");
     ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
     xml.Validate(eventHandler);
 }
Example #10
0
    public static void Validate(XmlDocument message)
    {
      string errMsgs = string.Empty;

      message.Validate((sender, args) => { errMsgs += args.Message; });

      if (!string.IsNullOrEmpty(errMsgs))
        throw new ArgumentOutOfRangeException(errMsgs);
    }
Example #11
0
        /// <summary>
        /// Validate the given XML against the schema.
        /// </summary>
        /// <param name="xmlDocument">An <see cref="XmlDocument"/>. The XML to validate.</param>
        /// <param name="schemas">An <see cref="XmlSchemaSet"/>. The schema to validate with.</param>
        public static void Validate(XmlDocument xmlDocument, XmlSchemaSet schemas)
        {
            if (xmlDocument == null)
            {
                throw new ArgumentNullException("xmlDocument");
            }

            xmlDocument.Schemas = schemas;
            xmlDocument.Validate(null);
        }
Example #12
0
 private void ValidateXML(XmlDocument inputXmlDocument)
 {
     inputXmlDocument.Schemas.Add("", new XmlTextReader(new StringReader(Resources.XmlServerReport)));
     inputXmlDocument.Validate(
         (o, e) =>
         {
             throw new CruiseControlRepositoryException(
                 "Invalid XML data. Does not validate against the schema", e.Exception);
         });
     inputXmlDocument.Schemas = null;
 }
Example #13
0
		public void ValidateXML ()
		{			      
			XmlReader reader = XmlReader.Create ("MyModels.xml");     
			XmlDocument document = new XmlDocument ();     

			document.Schemas.Add ("", "MyModels.xsd");     
			document.Load (reader);     

			document.Validate (new 
				ValidationEventHandler (ValidationEventHandler)); 
		}
Example #14
0
        /// <summary>
        /// Checks the schema validation.
        /// </summary>
        /// <param name="xml">The XML.</param>
        private static void CheckSchemaValidation(string xml)
        {
            var document = new XmlDocument();

            document.Schemas.Add("http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection",
                XmlReader.Create("IgniteConfigurationSection.xsd"));

            document.Load(new StringReader(xml));

            document.Validate(null);
        }
        public void ValidateXML(string xmlPath)
        {
            string xsdPath = @"Resources\person.xsd";
            Console.WriteLine("Validating " + xmlPath);

            XmlReader reader = XmlReader.Create(xmlPath);
            XmlDocument document = new XmlDocument();
            document.Schemas.Add("", xsdPath);
            document.Load(reader);
            document.Validate(ValidationEventHandler);
        }
Example #16
0
        /// <inheritdoc />
        public override void Apply(XmlDocument document, string key)
        {
            // Set the validation schemas
            document.Schemas = schemas;

            // Validate the document
            document.Validate((sender, e) =>
            {
                this.WriteMessage(key, MessageLevel.Warn, e.Message);
            });
        }
 public void Validate(XmlDocument doc)
 {
     doc.Schemas.Add(schemaset);
     doc.Validate(new ValidationEventHandler(OnValidateInfo));
     ErrorMessage = errors.ToString();
     WarningMessage = warnings.ToString();
     if (!string.IsNullOrEmpty(ErrorMessage))
     {
         throw new ConfigurationValidationException("Configuration validation failed:\n" + ErrorMessage);
     }
 }
		public override void Apply (XmlDocument document, string key) {

			// set the validate schema
			document.Schemas = schemas;

			// create a validation handler
			ValidationEventHandler handler = new ValidationEventHandler(LogValidationError);

			// validate the document
			document.Validate(handler);

		}
Example #19
0
        public static void ValidateXML()
        {
            string xsdPath = "Person.xsd";
            string xmlPath = "Person.xml";

            XmlReader reader = XmlReader.Create(xmlPath);
            XmlDocument document = new XmlDocument();
            document.Schemas.Add("", xsdPath);
            document.Load(reader);
            ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
            Console.WriteLine("Validating Person.xml ...");
            document.Validate(eventHandler);
        }
Example #20
0
        public static void save(IEnumerable<Employee> lst )
        {
            //XmlNamespaceManager xmlns = new XmlNamespaceManager();
            //xmlns.AddNamespace("tns","http://localhost/Employee.xsd");
            if (null == lst) return;
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", "yes"));
            bool haserror = false;
            doc.AppendChild(doc.CreateElement("Employees"));
            //doc.DocumentElement.SetAttribute("xmlns", "http://localhost/Employee.xsd");
            //doc.DocumentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            //doc.DocumentElement.SetAttribute("xsi:noNamespaceSchemaLocation", "Employee.xsd");

            foreach (Employee emp in _lst)
            {
                doc.ChildNodes[1].AppendChild(buildEmployeeNode(emp,doc));
            }

            doc.Save("_employees.xml");
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            XmlReader reader = XmlReader.Create("_employees.xml",settings);
            XmlSchema s = doc.Schemas.Add("http://localhost/Employee.xsd", "Employee.xsd");
            doc.Load(reader);
            try
            {
                doc.Validate((Object sender, ValidationEventArgs e) =>
                {
                    switch (e.Severity)
                    {
                        case XmlSeverityType.Error:
                            haserror = true;
                            break;
                        case XmlSeverityType.Warning:
                            break;
                        default:

                            break;
                    }
                });
            }
            catch (Exception e)
            {
            }
            finally
            {
                reader.Close();
                System.IO.File.Delete("_employees.xml");
            }
            if (!haserror) doc.Save("Employees.xml");
        }
Example #21
0
        public static bool ValidateSchema(XmlDocument doc, string schemaPath)
        {
            doc.Schemas.Add(null, schemaPath);

            try
            {
                doc.Validate(null);
                return true;
            }
            catch (XmlSchemaValidationException)
            {
                return false;
            }
        }
        public void ValidateXML()
        {
            string xsdPath = "person.xsd";
            string xmlPath = "person.xml";

            XmlReader reader = XmlReader.Create(xmlPath);
            var document = new XmlDocument();
            document.Schemas.Add("", xsdPath);
            document.Load(reader);

            ValidationEventHandler eventHandler =
                ValidationEventHandler;
            document.Validate(eventHandler);
        }
        public static void ValidateXML()
        {
            XmlReader reader = XmlReader.Create(XmlPath);
            XmlDocument document = new XmlDocument();
            document.Schemas.Add("", XsdPath);
            document.Load(reader);

            var eventHandler = new ValidationEventHandler(ValidationEventHandler);
            document.Validate(eventHandler);

            // If there is something wrong with the XML file, such as a non-existing element,
            // the Valid tionEventHandler is called.
            // Depending on the type of validation error, you can decide which action to take.
        }
        private static void ValidateXmlDocument(Type resourceType, XmlDocument xmlDocument, string xpath, string schemaResourceName)
        {
            using (System.IO.Stream schemaStream = GetXmlSchemaFromResource(resourceType, schemaResourceName))
            {
                if (schemaStream == null)
                    throw new Exception("Failed to read catalogue schema from resource.");

                XmlSchema xmlSchema = XmlSchema.Read(schemaStream, ValidationHandler);
                xmlDocument.Schemas.Add(xmlSchema);
                XmlNode xmlValidationNode = xmlDocument.SelectSingleNode(xpath);
                xmlDocument.Validate(ValidationHandler, xmlValidationNode);
                xmlDocument.Schemas.Remove(xmlSchema);
            }
        }
Example #25
0
        public static void ValidateXML()
        {
            string xsdPath = "Person.xsd";
            string xmlPath = "Person.xml";

            XmlReader reader = XmlReader.Create(xmlPath);
            XmlDocument document = new XmlDocument();
            document.Schemas.Add("", xsdPath);
            document.Load(reader);
            ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
            Console.WriteLine("Validating Person.xml ...");
            document.Validate(eventHandler);

            Console.WriteLine($"First child of root: {document.DocumentElement.FirstChild.Name} => {document.DocumentElement.FirstChild.InnerText}");
        }
Example #26
0
 public XPathNavigator ValidateXMLDoc( XmlDocument doc,
                                       String xsdPath )
 {
     XPathNavigator nav = doc.CreateNavigator();
     doc.Schemas.Add( null, xsdPath );
     ValidationEventHandler validation = 
         new ValidationEventHandler( SchemaValidationHandler );
     // G.CO( "Will validate document" );
     doc.Validate( validation );
     if ( m_validationError ) {
         return null;
     }
     // G.CO( "Validated document" );
     return nav;
 }
Example #27
0
        public MeshData LoadStream(Stream stream)
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            Console.WriteLine("Now loading schemas, this will be slow...");
            // Apparently .NET doesn't have the schema schema, so we have to have our own copy!  :D
            settings.Schemas.Add("http://www.w3.org/XML/1998/namespace", "xml.xsd");
            settings.Schemas.Add("http://www.collada.org/2005/11/COLLADASchema", "collada_schema_1_4");
            Console.WriteLine("Done!  Wasn't that horrible?");
            //Console.WriteLine("Gods, now we have to actually validate the Collada file...");
            settings.ValidationType = ValidationType.Schema;
            XmlReader reader = XmlReader.Create(stream, settings);
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);
            ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
            doc.Validate(eventHandler);

            //XmlNode geom = doc.SelectNodes("/COLLADA/library_geometries/mesh");

            return null;
            /*
            XmlReader textReader = new XmlTextReader(stream);
             textReader.Read();

            // If the node has value

            while (textReader.Read())
            {
                // Move to fist element
                textReader.MoveToElement();
                Console.WriteLine("XmlTextReader Properties Test");
                Console.WriteLine("===================");
                // Read this element's properties and display them on console
                Console.WriteLine("Name:" + textReader.Name);
                Console.WriteLine("Base URI:" + textReader.BaseURI);
                Console.WriteLine("Local Name:" + textReader.LocalName);
                Console.WriteLine("Attribute Count:" + textReader.AttributeCount.ToString());
                Console.WriteLine("Depth:" + textReader.Depth.ToString());
                //Console.WriteLine("Line Number:" + textReader.LineNumber.ToString());
                Console.WriteLine("Node Type:" + textReader.NodeType.ToString());
                Console.WriteLine("Attribute Count:" + textReader.Value.ToString());
            }

            XmlDocument d = new XmlDocument();
            XmlSchema s = new XmlSchema();

            return null;
            */
        }
 /// <summary>
 /// Valida un documento XML de un CFDI
 /// </summary>
 /// <param name="cfdi">Documento XML de CFDI</param>
 /// <param name="xsd">Documento XSD</param>
 /// <returns></returns>
 public static bool Validar(string cfdi, string xsd)
 {
     try {
     XmlDocument doc = new XmlDocument();
     XmlSchemaSet esq = new XmlSchemaSet();
     doc.LoadXml(cfdi);
     esq.Add(XmlSchema.Read(XmlReader.Create(xsd), ValidationCallback));
     doc.Schemas = esq;
     doc.Validate((o, e) => {
                           throw new Exception("ERROR: " + e.Message);
                  });
     // Si no ocurre ninguna excepcion es válido
     return true;
      } catch(Exception) {
     return false;
      }
 }
Example #29
0
 public bool ValidXmlDoc(XmlDocument xmlDoc, string targetNamespace, XmlReader xmlRdr)
 {
     _isValidXml = true;
     _validationError = "";
     try
     {
         xmlDoc.Schemas.Add(targetNamespace, xmlRdr);
         var veh = new ValidationEventHandler(ValidationCallBack);
         xmlDoc.Validate(veh);
     }
     catch (Exception ex)
     {
         _isValidXml = false;
         Console.Out.WriteLine("ValidXmlDoc: " + ex.Message);
     }
     return _isValidXml;
 }
Example #30
0
        /// <summary>
        /// Возвращает список клиентов прочитанный из указанного XML файла с помощью класса XmlDocument
        /// </summary>
        /// <param name="customersXmlPath">Путь к файлу customers.xml</param>
        /// <param name="customersXsdPath">Путь к файлу customers.xsd</param>
        /// <returns>Cписок клиентов</returns>
        /// <remarks>Обратите внимание, что мы всегда возврашаем коллекцию даже если ничего не прочитали из файла</remarks>
        public static List<Customer> GetCustomersUsingXmlDocument(string customersXmlPath, string customersXsdPath = null)
        {
            var customers = new List<Customer>();

            var xmlDoc = new XmlDocument();
            xmlDoc.Load(customersXmlPath);
            if (customersXsdPath != null)
            {
                xmlDoc.Schemas.Add(CUSTOMERS_NAMESPACE, customersXsdPath);

                try
                {
                    xmlDoc.Validate(null);
                }
                catch (XmlSchemaValidationException ex)
                {
                    throw new CustomerLoadFailedException("Customer.xml has some errors", ex);
                }
            }

            var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
            nsmgr.AddNamespace("c", CUSTOMERS_NAMESPACE);

            XmlNodeList customerNodes = xmlDoc.DocumentElement.SelectNodes("c:Customer", nsmgr);
            foreach (XmlElement customerNode in customerNodes)
            {
                var customer = new Customer { CustomerId = customerNode.GetAttribute("CustomerId") };

                XmlNode companyNameNode = customerNode.SelectSingleNode("c:CompanyName", nsmgr);
                if (companyNameNode != null)
                {
                    customer.CompanyName = companyNameNode.InnerText;
                }

                XmlNode countryNode = customerNode.SelectSingleNode("c:FullAddress/c:Country", nsmgr);
                if (countryNode != null)
                {
                    customer.Country = countryNode.InnerText;
                }

                customers.Add(customer);
            }

            return customers;
        }