XDocument.Validate is always successful

2020-01-25 02:42发布

问题:

I have a schema file which does not define any target namespaces, i.e. its definition looks like this:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <!--Elements, attributes, etc. -->
</xs:schema>

The corresponding XML looks like this:

<Documents p1:CRC="0" p1:Date="1900-01-01T01:01:01+01:00" p1:Name="Test" p1:Status="new" xmlns:p1="http://www.tempuri.org/pdms.xsd" xmlns="http://www.tempuri.org/pdms.xsd">
  <p1:Document p1:Date="2010-12-23T07:59:45" p1:ErrorCode="0" p1:ErrorMessage="" p1:Number="TEST00001" p1:Status="new"/>
</Documents>

Validation of this XML against the schema with e.g. Altova XMLSpy or Oxygen XML Editor fails.

However my validation in C# (.NET 4.0) does not fail. The XML is processed as an XDocument object. If I have understood correctly then XDocument.Validate() does a lax validation if no namespace is found in the schema. Thus the validation does not fail. But then how can I implement a "strict" validation for XDocument?

This is how I try to validate the XML:

public static void ValidateXml(XDocument xml, string xsdFilename) {
  XmlReaderSettings settings = new XmlReaderSettings();
  XmlSchemaSet schemaSet = new XmlSchemaSet();

  schemaSet.Add(string.empty, xsdFilename);
  settings.ValidationType = ValidationType.Schema;
  settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
  settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);

  xml.Validate(schemaSet, ValidationCallback);
}

private static void ValidationCallback(object sender, ValidationEventArgs args) {
  if (args.Severity == XmlSeverityType.Warning) {
    // Do warning stuff...
  } else if (args.Severity == XmlSeverityType.Error) {
    // Do error stuff...
  }
}

回答1:

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.