Possible to validate xml against xsd using code at runtime?
Asked Answered
A

3

11

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#

Alcus answered 14/8, 2009 at 12:30 Comment(0)
O
16

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);
}
Ocular answered 14/8, 2009 at 12:57 Comment(1)
this is the fastest one, I've used.Focalize
M
5

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.

Mcmillian answered 14/8, 2009 at 13:13 Comment(1)
You might want to try using the XmlSchema.Read method, since it can validate the schema while parsing it.Ocular
A
3

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());
        }
Aube answered 20/10, 2009 at 6:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.