internal ValidationResult(ValidationResult init) { this.Success = init.Success; this.Line = init.Line; this.Column = init.Column; this.SourceFile = init.SourceFile; this.Exception = init.Exception; }
/// <summary> /// Validates the specified document <paramref name="document"/> against the XML schema loaded from the specified /// <paramref name="schemaPath"/>, and returns an object that contains the validation information. /// </summary> /// <param name="document">The document to validate.</param> /// <param name="schemaPath">The path to the XML schema to use to validate the document against.</param> /// <returns>An object that contains the validation information</returns> public static ValidationResult ValidateDocument(XmlDocument document, string schemaPath) { Contract.Requires<ArgumentNullException>(document != null); Contract.Requires<ArgumentNullException>(!string.IsNullOrWhiteSpace(schemaPath)); ValidationResult result = new ValidationResult(); XmlSchemaSet schemaSet = null; if (!string.IsNullOrWhiteSpace(schemaPath)) { UrlResolver resolver = new UrlResolver(); XmlReaderSettings settings = CacheableXmlDocument.CreateReaderSettings(resolver); XmlReader reader = XmlReader.Create(schemaPath, settings); XmlSchema schema = XmlSchema.Read(reader, null); schemaSet = new XmlSchemaSet { XmlResolver = resolver }; schemaSet.Add(schema); schemaSet.Compile(); } XDocument xdocument = XDocument.Parse(document.OuterXml, LoadOptions.SetLineInfo); xdocument.Validate(schemaSet, (sender, args) => { if (args.Severity == XmlSeverityType.Error) { result.Success = false; var lineInfo = sender as IXmlLineInfo; if (lineInfo != null) { result.Exception = new XmlException(args.Message, args.Exception, lineInfo.LineNumber, lineInfo.LinePosition); } else { result.Exception = args.Exception; } } }); return result; }