tags:

views:

247

answers:

1

I got this weird error when I wanted to validate my in-memory xml Schema, anything I did wrong?

    [Test]
    public void ValidationXML()
    {
        int errorCount = 0;
        var xmlString = "<?xml version='1.0'?><response><error code='1'> Success</error></response>";
        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(xmlString);
        xmlDocument.Validate((sender, e) => errorCount++);
        Assert.AreEqual(0, errorCount);
    }

The exception was:

 failed: System.InvalidOperationException : The XmlSchemaSet on the document is either null or has no schemas in it. Provide schema information before calling Validate.
    at System.Xml.XmlDocument.Validate(ValidationEventHandler validationEventHandler, XmlNode nodeToValidate)
    at System.Xml.XmlDocument.Validate(ValidationEventHandler validationEventHandler)
+2  A: 

You are trying to validate the XmlDocument without assigning a schema to check against.

xmlDocument.Schemas.Add(new XmlSchema());

This tries to validate against an empty schema (as opposed to null) and will fail the validation (instead of throwing an exception), setting errorCount to 1.

Luis