Advertisement
Guest User

Validator XML - XSD

a guest
Nov 8th, 2018
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.54 KB | None | 0 0
  1. public class Validator
  2.     {
  3.         private string xml_filename_;
  4.         private string xsd_filename_;
  5.  
  6.         private bool is_success_;
  7.  
  8.         public Validator()
  9.         {
  10.  
  11.             is_success_ = false;
  12.         }
  13.  
  14.         public void setValidate(string xml_filename, string xsd_filename) {
  15.             xml_filename_ = xml_filename;
  16.             xsd_filename_ = xsd_filename;
  17.         }
  18.  
  19.         public bool Validate()
  20.         {
  21.             is_success_ = false;
  22.  
  23.             XmlDocument document = new XmlDocument();
  24.             document.Load(xml_filename_);
  25.  
  26.             XmlReaderSettings setting = new XmlReaderSettings();
  27.             setting.CloseInput = true;
  28.             setting.ValidationEventHandler += Handler;
  29.             setting.ValidationType = ValidationType.Schema;
  30.             setting.Schemas.Add(null, xsd_filename_);
  31.             setting.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings |
  32.                                       XmlSchemaValidationFlags.ProcessIdentityConstraints |
  33.                                       XmlSchemaValidationFlags.ProcessInlineSchema |
  34.                                       XmlSchemaValidationFlags.ProcessSchemaLocation;
  35.  
  36.             is_success_ = true;
  37.  
  38.             using (XmlReader validationReader = XmlReader.Create(xml_filename_, setting))
  39.             {
  40.                 while (validationReader.Read())
  41.                 {
  42.                     /* do nothing for while */
  43.                 }
  44.             }
  45.  
  46.             return is_success_;
  47.         }
  48.  
  49.         private void Handler(object sender, ValidationEventArgs e)
  50.         {
  51.             if (e.Severity == XmlSeverityType.Error ||
  52.                 e.Severity == XmlSeverityType.Warning)
  53.             {
  54.                 System.Console.WriteLine(String.Format("Line: {0}, Position: {1} '{2}'",
  55.                     e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message));
  56.  
  57.                 is_success_ = false;
  58.             }
  59.         }
  60.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement