Why is the XmlDocument Validate event handler not

2019-03-01 14:39发布

问题:

I have this code:

  // Load the document
  XmlDocument xmlDocument = new XmlDocument();

  // use the stream and have it close when it is finished
  using ( argInputStream )
  {
    xmlDocument.Load( argInputStream );
    xmlDocument.Schemas.Add( XmlSchema.Read( argSchemaStream, null ) );
    xmlDocument.Validate( ValidationEventHandler );
  }

// this is not getting hit
void ValidationEventHandler( object sender, ValidationEventArgs e )
{
  switch ( e.Severity )
  {
    case XmlSeverityType.Error:
      Console.WriteLine( "Error: {0}", e.Message );
      break;
    case XmlSeverityType.Warning:
      Console.WriteLine( "Warning {0}", e.Message );
      break;
  }
}

top line of my XSD:

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" 
xmlns:xs="http://www.w3.org/2001/XMLSchema">

Any ideas?

回答1:

I've got some code validating xml using this construction.

var schemaReader = new XmlTextReader(argSchemaStream);
var schema = new XmlSchemaSet();
schema.Add(null, schemaReader);

var settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(schema);
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);

var doc = new XmlDocument();
doc.Load(XmlReader.Create(argInputStream, settings));


回答2:

I don't think it is the correct way of validating; try this MSDN link. Basically, the schema seems to go with the XmlReaderSettings instead.

XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(...);
settings.ValidationType = ValidationType.Schema;

XmlReader reader = XmlReader.Create(..., settings);
XmlDocument document = new XmlDocument();
document.Load(reader);

document.Validate(eventHandler);