2

我有这个代码:

  // 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;
  }
}

我的 XSD 的第一行:

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

有任何想法吗?

4

2 回答 2

3

我有一些使用这种结构验证 xml 的代码。

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));
于 2012-06-05T19:07:24.793 回答
0

我认为这不是正确的验证方式;试试这个MSDN 链接。基本上,架构似乎与 XmlReaderSettings 一起使用。

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);
于 2012-06-05T19:03:13.033 回答