XDocument.Validate is always successful

I am not sure it is possible to use the Validate method; if you use a validating XmlReader over the XDocument where ValidationFlags are set up to emit validation warnings, as in

        XDocument doc = XDocument.Load("../../XMLFile1.xml");

        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.Add(null, "../../XMLSchema1.xsd");

        XmlReaderSettings xrs = new XmlReaderSettings();
        xrs.ValidationType = ValidationType.Schema;
        xrs.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
        xrs.Schemas = schemaSet;
        xrs.ValidationEventHandler += (o, s) => {
            Console.WriteLine("{0}: {1}", s.Severity, s.Message);
        };

        using (XmlReader xr = XmlReader.Create(doc.CreateReader(), xrs))
        {
            while (xr.Read()) { }
        }

then the ValidationEventHandler does emit a warning for each node it does not find schema information for. So your ValidationEventHandler could check for such warnings. But you might as well simply compare the doc.Root.Name.Namespace with the target namespace of the schemas you have before calling the Validate method.

Leave a Comment