Question

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#

Was it helpful?

Solution

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);
}

OTHER TIPS

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.

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());
        }

Hope this link helps:

Validation of XML with XSD

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top