0

Have have been trying to make a validator for my xml files. I have used some of the other examples that can be found on this site (like How to validate an XML document?).

I just don't see it working the way I expect. What does actually get validated?

Almost no matter what I change in the xml file, the validator dosent sees it as an error. I thought the validator would see if the xml file contains an element not defined in the xsd. The validator only catches normal xml syntax errors.

So whats the point of using the xsd if it doesn't have an influence?

My validator

string xsd_file = "Message.xsd";
XmlSchema xsd = new XmlSchema();
xsd.SourceUri = xsd_file;

XmlSchemaSet ss = new XmlSchemaSet();
ss.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
ss.Add(null, xsd_file);
if (ss.Count > 0)
{
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas.Add(ss);
    settings.Schemas.Compile();
    settings.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
    XmlTextReader r = new XmlTextReader(filepath);
    using (XmlReader reader = XmlReader.Create(r, settings))
    {
        try
        {
            while (reader.Read())
            {
            }
        }
        catch (XmlException ex)
        {

            throw;
        }                        
    }
}
Community
  • 1
  • 1
Christian
  • 1,080
  • 1
  • 20
  • 37
  • 1
    Take a look at this [SO post and the response][1]. It explains in details how to do validation. [1]: http://stackoverflow.com/questions/9806346/single-pass-read-and-validate-xml-vs-referenced-xsd-in-c-sharp – Petru Gardea Mar 23 '12 at 15:54

1 Answers1

0

The code for the validation eventhandler is missing.

Looking at my working code which is slightly different I have this

settings.ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ReportValidationFlags;

Can't remember why I had to add it though.

First thing to do is make sure the eventhandler is getting triggered, after that it may be a problem with your xsd.

Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39