public XsdValidationResult ValidateInstance(string xsdFilePath, string instanceDoc) { 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"); } if (!FileHelper.FileExists(xsdFilePath)) { throw new ArgumentException(string.Format("The Xsd file '{0}' dooes not exist. Please specify a valid file.", xsdFilePath)); } FileInfo info = new FileInfo(xsdFilePath); Environment.CurrentDirectory = info.DirectoryName; StreamReader reader = new StreamReader(xsdFilePath); XmlTextReader reader2 = new XmlTextReader(reader.BaseStream); XsdValidationResult result = ValidateInstance(reader2, instanceDoc); Environment.CurrentDirectory = Environment.CurrentDirectory; return(result); }
private static string onSearchClicked(BulkWindow.BulkCommunicator bc, ICollection <string> files, object userObject) { bc.ReportProgress(string.Format("Found {0} files to scan", files.Count)); StringBuilder edtResult = new StringBuilder(); int countFiles = 0, countWarnings = 0, countErrors = 0, countSuccess = 0; try { foreach (string file in files) { try { bc.ReportProgress("Scanning file: " + file); edtResult.Append("Result of file: " + file + " ..."); try { countFiles++; XmlDocument xmldoc = File.ReadAllText(file).ToXmlDocument(); XsdValidationResult result = XsdValidationHelper.Instance.ValidateInstance( userObject.ToString(), File.ReadAllText(file)); switch (result.State) { case ValidationState.Success: edtResult.Append(" valid"); countSuccess++; break; case ValidationState.Warning: edtResult.Append(" warning"); countWarnings++; break; case ValidationState.ValidationError: edtResult.Append(" error"); countErrors++; break; case ValidationState.OtherError: edtResult.Append(" other error"); countErrors++; break; } } catch (Exception ex) { edtResult.Append(ex.Message); countErrors++; } edtResult.AppendLine(); } catch (Exception e) { edtResult.AppendLine("Error while scanning " + file + ": " + e.Message); } } edtResult.AppendLine(); edtResult.AppendFormat("{0} files, {1} valid, {2} valid with warnings, {3} errors", countFiles, countSuccess, countWarnings, countErrors); edtResult.AppendLine(); edtResult.AppendLine("Scanning completed"); } catch (Exception e) { edtResult.AppendLine("Error: " + e.Message); } return(edtResult.ToString()); }
void validationUpdateTimer_Tick(object sender, EventArgs e) { Debug.Assert(_editor != null); _lstErrors.Items.Clear(); _errorMarker.ClearMarks(); try { if (_validationData.DoNotValidate) { var i1 = new ValidationIssue(ValidationIssue.Type.Information, 0, 0, "Validation is turned off.\nTo activate, click in ribbon on 'Validation' tab and select 'Check wellformedness' or 'Validate against schema'."); _lstErrors.Items.Add(i1); } else if (_validationData.CheckWellformedness) { try { XmlDocument xmlDoc = _editor.XmlEditor.Text.ToXmlDocument(); //TODO make async var i = new ValidationIssue(ValidationIssue.Type.Information, 0, 0, "XML is wellformed"); _lstErrors.Items.Add(i); } catch (XmlException ex) { var i = new ValidationIssue(ValidationIssue.Type.Error, ex.LineNumber, ex.LinePosition, ex.Message); _lstErrors.Items.Add(i); } } else if (_validationData.CheckXsd) { string xsdFile = _validationData.Xsd; if (!FileHelper.FileExists(xsdFile)) { var i = new ValidationIssue(ValidationIssue.Type.Warning, 0, 0, $"The file '{xsdFile}' does not exist, or the path is invalid"); _lstErrors.Items.Add(i); return; } XsdValidationResult result = XsdValidationHelper.Instance.ValidateInstance( xsdFile, _editor.XmlEditor.Text); if (result.Results.Count == 0) { var i = new ValidationIssue(ValidationIssue.Type.Information, 0, 0, "XML is valid"); _lstErrors.Items.Add(i); } else { foreach (var x in result.Results) { _lstErrors.Items.Add(x); } } } } catch (Exception ex) { var i = new ValidationIssue(ValidationIssue.Type.Error, 0, 0, "Error while validating file: " + ex.Message); _lstErrors.Items.Add(i); } foreach (var item in _lstErrors.Items) { var error = item as ValidationIssue; if (error != null) { if (error.IssueType != ValidationIssue.Type.Information) { int offset = error.Line == 0 ? 0 : _editor.XmlEditor.Document.GetOffset(error.Line, error.Column); _errorMarker.AddOffsetToMark(new MarkBackgroundRenderer.Mark { Offset = offset, Length = 1, Brush = new SolidColorBrush(Color.FromArgb(0x40, 0xFF, 0, 0)) }); } } } }
public XsdValidationResult ValidateInstance(XmlTextReader xsdReader, string instanceDoc) { _result = new XsdValidationResult(); try { XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; //settings.ValidationFlags = XmlSchemaValidationFlags.ProcessSchemaLocation; try { settings.Schemas.Add(null, xsdReader); } catch (Exception ex) { throw new Exception("Invalid schema file: " + ex.Message, ex); } settings.ValidationEventHandler += settings_ValidationEventHandler; List <string> list = new List <string>(); foreach (XmlSchema schema in settings.Schemas.Schemas()) { if (!string.IsNullOrEmpty(schema.TargetNamespace)) { list.Add(schema.TargetNamespace); } } XmlReader reader2 = XmlReader.Create(instanceDoc.ToStream(), settings); while (reader2.Read()) { } if (_result.State == ValidationState.Success) { XmlDocument xd = instanceDoc.ToXmlDocument(); if (!list.Contains(xd.DocumentElement.NamespaceURI)) { StringBuilder builder = new StringBuilder(); builder.AppendLine("The namespace of the current document does not match any of the target namespaces for the loaded schemas."); builder.AppendLine("Have you specified the correct schema for the current document?"); builder.AppendLine("Document Namespace:\t"); builder.AppendLine(xd.DocumentElement.NamespaceURI); builder.AppendLine("Schema Target Namespace(s):"); if (list.Count == 0) { builder.Append("\t(None)"); } else { foreach (string t in list) { builder.Append("\t"); builder.AppendLine(t); } } var vi = new ValidationIssue(ValidationIssue.Type.Information, 0, 0, builder.ToString()); _result.Results.Add(vi); _result.State = ValidationState.Warning; } } } catch (XmlSchemaException exception) { string text = string.Format("Invalid xsd file ({0}:{1}): {2}", exception.LineNumber, exception.LinePosition, exception.Message); var vi = new ValidationIssue(ValidationIssue.Type.Error, 0, 0, text); _result.Results.Add(vi); _result.State = ValidationState.OtherError; } catch (XmlException exception) { var vi = new ValidationIssue(ValidationIssue.Type.Error, exception.LineNumber, exception.LinePosition, exception.Message); _result.Results.Add(vi); _result.State = ValidationState.OtherError; } catch (Exception exception) { var vi = new ValidationIssue(ValidationIssue.Type.Error, 0, 0, exception.Message); _result.Results.Add(vi); _result.State = ValidationState.OtherError; } finally { if (xsdReader != null) { xsdReader.Close(); } } return(_result); }