Azeem Hafeez
Azeem Hafeez

Reputation: 250

How to validate xml file schema,data and sequence with xsd file in c#?

I am validating XML Schema with XSD file using below code. Its working fine. Now i want to validate XML schema, data and their sequence with XSD file. How i can do this. Thanks in advance for help.

FileStream fs = new FileStream(@"D:\Intra\INTTRA.xsd", FileMode.Open);
XmlSchema schema = XmlSchema.Read(fs, ValidationCallBack);
schema.TargetNamespace = "http://xml.inttra.com/booking/services/01";
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(schema);
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationEventHandler += new      
ValidationEventHandler(ValidationCallBack);
XDocument doc = XDocument.Load(@"D:\Intra\BookingRequest_07032017_153200.xml");
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(doc.ToString());
writer.Flush();
stream.Position = 0;
XmlReader xr = XmlReader.Create(stream, settings);

while (xr.Read())
{
   string s = xr.Name;
   Console.WriteLine(s + "<br/>");
}

fs.Close();

Upvotes: 0

Views: 471

Answers (1)

J.SMTBCJ15
J.SMTBCJ15

Reputation: 499

We do it like this

private void ValidateRequest(string xmlPayload)
{
   XmlTextReader xsdReader = null;
   XmlSchemaSet xsdSchema = null;
   XmlReaderSettings xmlReader = null;

   xsdReader = new XmlTextReader("your xsd file path here");
   xsdSchema = new XmlSchemaSet();
   xsdSchema.Add(null, xsdReader);
   xsdSchema.Compile();

   xmlReader = new XmlReaderSettings();

   xmlReader.ValidationType = ValidationType.Schema;
   xmlReader.Schemas.Add(xsdSchema);
   xmlReader.ValidationEventHandler += vr_ValidationEventHandler;

   XmlReader reader = XmlReader.Create(new StringReader(xmlPayload), xmlReader);
     while (reader.Read()) ;
     reader.Close();
}

void vr_ValidationEventHandler(object sender, ValidationEventArgs e)
{
    switch (e.Severity)
    {
        case XmlSeverityType.Error:
            throw new Exception(e.Message);
        case XmlSeverityType.Warning:
            break;
    }
}

Upvotes: 1

Related Questions