Пример #1
0
        protected override void Execute(EditorFrame ef)
        {
            if (ef.XSDocument == null)
            {
                throw new Exception("Parameter must be TextEditor");
            }

            OpenFileDialog dlgOpenFile = new OpenFileDialog();

            dlgOpenFile.Filter = "Xml Files (*.xml)|*.xml";
            dlgOpenFile.Title  = "Select an Xml file to validate";

            if (dlgOpenFile.ShowDialog() == true)
            {
                try
                {
                    var file = dlgOpenFile.FileName;
                    var xsd  = new XmlTextReader(new StringReader(ef.XmlEditor.Text));

                    XsdValidationResult result = XsdValidationHelper.Instance.ValidateInstance(
                        xsd, File.ReadAllText(file));
                    switch (result.State)
                    {
                    case ValidationState.Success:
                        MessageBox.Show(Application.Current.MainWindow, "Document is valid", "Validation result",
                                        MessageBoxButton.OK, MessageBoxImage.Information);
                        break;

                    case ValidationState.Warning:
                        MessageBox.Show(Application.Current.MainWindow, "Document is valid with warnings", "Validation result",
                                        MessageBoxButton.OK, MessageBoxImage.Warning);
                        break;

                    case ValidationState.ValidationError:
                        MessageBox.Show(Application.Current.MainWindow, "Document is invalid", "Validation result",
                                        MessageBoxButton.OK, MessageBoxImage.Error);
                        break;

                    case ValidationState.OtherError:
                        MessageBox.Show(Application.Current.MainWindow, "Document is invalid", "Validation result",
                                        MessageBoxButton.OK, MessageBoxImage.Error);

                        break;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(Application.Current.MainWindow, "Error: " + ex.Message, "Validation result",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        /// <summary>
        /// Validates an xml document against an xsd file
        /// </summary>
        /// <param name="xsdFilePath">Path to the xsd file</param>
        /// <param name="xmlFilePath">Xml document to be validated</param>
        /// <returns>Results of the validation</returns>
        public XsdValidationResult ValidateInstance(string xsdFilePath, XmlDocument instanceDoc)
        {
            // Sanity check parameters
            if (string.IsNullOrEmpty(xsdFilePath))
            {
                throw new ArgumentNullException("xsdFilePath", "An Xsd File Path must be given");
            }
            if (instanceDoc == null)
            {
                throw new ArgumentNullException("instanceDoc", "A valid instance XmlDocument must be supplied");
            }

            // Check existence of Xsd File
            if (!FileHelper.Instance.FileExists(xsdFilePath))
            {
                throw new ArgumentException(string.Format("The Xsd file '{0}' dooes not exist. Please specify a valid file.", xsdFilePath));
            }

            // Load in the schema to a stream
            StreamReader xsdReader = null;
            FileInfo     fi        = new FileInfo(xsdFilePath);

            // Change the current diretcory to the schema location
            // in case there are relative schema locations (for import/include)
            string currentDirectory = Environment.CurrentDirectory;

            Environment.CurrentDirectory = fi.DirectoryName;

            // Load in the schema
            xsdReader = new StreamReader(xsdFilePath);
            XmlTextReader trSchema = new XmlTextReader(xsdReader.BaseStream);

            // Call the overload
            XsdValidationResult result = ValidateInstance(trSchema, instanceDoc);

            // Reset the current directory
            Environment.CurrentDirectory = currentDirectory;

            return(result);
        }
        /// <summary>
        /// Effettua la validazio dell'xDocument dato un set di schemas
        /// </summary>
        /// <param name="xml">Xml da validare</param>
        /// <param name="xmlSchemas">Xsd Schema</param>
        /// <returns>Validation Result</returns>
        /// <exception cref="InvalidOperationException">Xml null</exception>
        /// <exception cref="ArgumentNullException">schema null</exception>
        public static XsdValidationResult ValidateXml(this XDocument xml, XmlSchemaSet xmlSchemas)
        {
            if (xml == null)
            {
                throw new InvalidOperationException("Non è possibile validare un xml vuoto");
            }
            if (xmlSchemas == null)
            {
                throw new ArgumentNullException(nameof(xmlSchemas));
            }

            var result = new XsdValidationResult();

            xml.Validate(
                xmlSchemas,
                (o, e) =>
            {
                result.Add(new XsdValidationInfo(e.Message, e.Exception));
            });

            return(result);
        }
        /// <summary>
        /// Validates an xml document against an xsd file
        /// </summary>
        /// <param name="xsdFilePath">XmlTextReader containing an xsd file</param>
        /// <param name="xmlFilePath">Xml document to be validated</param>
        /// <returns>Results of the validation</returns>
        public XsdValidationResult ValidateInstance(XmlTextReader reader, XmlDocument instanceDoc)
        {
            _result = new XsdValidationResult();

            try
            {
                // Create an XmlReaderSettings object and load the schema into it.
                // This will also load in any imported/included schemas.
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.ValidationType  = ValidationType.Schema;
                settings.ValidationFlags = XmlSchemaValidationFlags.ProcessSchemaLocation;
                settings.Schemas.Add(null, reader);

                // Setup the event handler to handle errors/warnings
                settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);

                // Get the list of all targetNamespaces from the loaded schemas
                List <string> namespaces = new List <string>();
                foreach (XmlSchema s in settings.Schemas.Schemas())
                {
                    if (!string.IsNullOrEmpty(s.TargetNamespace))
                    {
                        namespaces.Add(s.TargetNamespace);
                    }
                }

                // Load the current Xml Document into a stream
                MemoryStream stream = new MemoryStream();
                instanceDoc.Save(stream);
                stream.Position = 0L;

                // Create the validating reader
                XmlReader vr = XmlReader.Create(stream, settings);

                // Read the document stream - this will validate as it reads
                while (vr.Read())
                {
                }

                // Check if we successfully validated the document
                if (_result.State == ValidationState.Success)
                {
                    _result.Results.AppendLine("No validation errors found.");

                    // Check if the document namespace matches any of the schema namespaces
                    if (!namespaces.Contains(instanceDoc.DocumentElement.NamespaceURI))
                    {
                        // Store the schema namespaces in a single string
                        StringBuilder schemaNSs = new StringBuilder();
                        if (namespaces.Count == 0)
                        {
                            schemaNSs.Append("\t");
                            schemaNSs.AppendLine("(None)");
                        }
                        else
                        {
                            for (int nsIndex = 0; nsIndex < namespaces.Count; nsIndex++)
                            {
                                schemaNSs.Append("\t");
                                schemaNSs.AppendLine(namespaces[nsIndex]);
                            }
                        }

                        // Add a warning that namespaces don't match
                        _result.Results.AppendLine();
                        _result.Results.AppendLine("Warning: The namespace of the current document does not match any of the target namespaces for the loaded schemas.");
                        _result.Results.AppendLine("Have you specified the correct schema for the current document?");
                        _result.Results.AppendLine();
                        _result.Results.AppendLine("Document Namespace:");
                        _result.Results.Append("\t");
                        _result.Results.AppendLine(instanceDoc.DocumentElement.NamespaceURI);
                        _result.Results.AppendLine();
                        _result.Results.AppendLine("Schema Target Namespace(s):");
                        _result.Results.AppendLine(schemaNSs.ToString());
                        _result.State = ValidationState.Warning;
                    }
                }
            }
            catch (Exception ex)
            {
                _result.Results.AppendLine("An error occurred: " + ex.Message);
                _result.State = ValidationState.OtherError;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }

            return(_result);
        }