tags:

views:

1212

answers:

4

I have xml files that I read in at runtime, is is possible to validate the xml against an xsd file at runtime? using c#

+2  A: 

Hi, http://www.codeguru.com/csharp/csharp/cs%5Fdata/xml/article.php/c6737 hope this link helps Best Regards, Iordan

IordanTanev
The link looks decent, but I noticed the example is using an XmlValidatingReader, which is obsolete. Take a look at the stock XmlReader and XmlReaderSettings which contains some Validation properties to define the behavior.
STW
+8  A: 

Try this:

public void ValidateXmlDocument(
    XmlReader documentToValidate, string schemaPath)
{
    XmlSchema schema;
    using (var schemaReader = XmlReader.Create(schemaPath))
    {
        schema = XmlSchema.Read(schemaReader, ValidationEventHandler);
    }

    var schemas = new XmlSchemaSet();
    schemas.Add(schema);

    var settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas = schemas;
    settings.ValidationFlags =
        XmlSchemaValidationFlags.ProcessIdentityConstraints |
        XmlSchemaValidationFlags.ReportValidationWarnings;
    settings.ValidationEventHandler += ValidationEventHandler;

    using (var validationReader = XmlReader.Create(documentToValidate, settings))
    {
        while (validationReader.Read())
        {
        }
    }
}

private static void ValidationEventHandler(
    object sender, ValidationEventArgs args)
{
    if (args.Severity == XmlSeverityType.Error)
    {
        throw args.Exception;
    }

    Debug.WriteLine(args.Message);
}
John Saunders
+3  A: 

I GOT CODE TOO! I use this in my tests:

 public static bool IsValid(XElement element, params string[] schemas)
 {
  XmlSchemaSet xsd = new XmlSchemaSet();
  XmlReader xr = null;
  foreach (string s in schemas)
  { // eh, leak 'em. 
   xr = XmlReader.Create(
                new MemoryStream(Encoding.Default.GetBytes(s)));
   xsd.Add(null, xr);
  }
  XDocument doc = new XDocument(element);
  var errored = false;
  doc.Validate(xsd, (o, e) => errored = true);
  if (errored)
   return false;

  // If this doesn't fail, there's an issue with the XSD.
  XNamespace xn = XNamespace.Get(
                      element.GetDefaultNamespace().NamespaceName);
  XElement fail = new XElement(xn + "omgwtflolj/k");
  fail.SetAttributeValue("xmlns", xn.NamespaceName);
  doc = new XDocument(fail);
  var fired = false;
  doc.Validate(xsd, (o, e) => fired = true);
  return fired;
 }

This one takes in the schemas as strings (file resources within the assembly) and adds them to a schema set. I validate and if its not valid I return false.

If the xml isn't found to be invalid, I do a negative check to make sure my schemas aren't screwed up. Its not guaranteed foolproof, but I have used this to find errors in my schemas.

Will
You might want to try using the `XmlSchema.Read` method, since it can validate the schema while parsing it.
John Saunders
A: 

simpler solution..

        try
        {
            XmlReaderSettings Xsettings = new XmlReaderSettings();
            Xsettings.Schemas.Add(null, "personDivideSchema.xsd");
            Xsettings.ValidationType = ValidationType.Schema;

            XmlDocument document = new XmlDocument();
            document.Load("person.xml");

            XmlReader reader = XmlReader.Create(new StringReader(document.InnerXml), Xsettings);


            while (reader.Read());
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
        }
chandler