I have implemented the xmlSchemaCollection object to cache commonly
used schemas, as follows:
===============================================================================
public void SchemaValidate(XmlDocument xmlDoc, string schemaURI,
string urnNamespace)
{
if (!m_SchemaCollection.Contains(urnNamespace))
{
//add new schema to collection cache if appropriate
m_SchemaCollection.Add(urnNamespace,schemaURI);
}
//set up validating reader
XmlValidatingReader reader = new XmlValidatingReader(
xmlDoc.OuterXml,
XmlNodeType.Document,
null);
reader.Namespaces = true;
reader.Schemas.Add(m_SchemaCollection);
reader.ValidationType = ValidationType.Schema;
ValidationEventHandler EvtHandler = new
ValidationEventHandler(this.ValidationCallBack);
reader.ValidationEventHandler += EvtHandler;
while (reader.Read())
{
//iterate entire document,building up XML Doc of ValidationErrors
}
if (m_ValErrorsXmlDoc.HasChildNodes)
{
#if DEBUG
m_ValErrorsXmlDoc.Save("C:\\temp\\debug\\SchemaValidationErrors.xml");
#endif
throw new Exception("Schema Validation Errors:" +
Environment.NewLine + schemaURI + Environment.NewLine +
m_ValErrorsXmlDoc.OuterXml);
}
}
===============================================================================
The caching seems to work fine, but I get validation errors on xs:any
elements. The reader complains that elements contained are not
declared..
I suspect I will have problems with xs:choice elements too.
Using the validating reader without the schema collection, the input
validates OK .. ie. as follows:
===============================================================================
public XmlDocument SchemaValidate(string XML, string RulesSchema)
{
XmlValidatingReader reader = new XmlValidatingReader(
XML,
XmlNodeType.Document,
null);
XmlReader schemaReader = new XmlTextReader(RulesSchema);
XmlSchema schema = XmlSchema.Read(schemaReader, new
ValidationEventHandler(ValidationCallBack));
reader.Schemas.Add(schema);
while (reader.Read())
{
//iterate entire document,building up XML Doc of ValidationErrors
}
XmlDocument xml = new XmlDocument();
xml.Load(reader);
//xml.LoadXml(RulesXML);
return xml;
}
===============================================================================
I have a vague idea that this is related to serialization of the
cached schemas? but am just guessing. I have spent a day on this
already...
Any help would be much appreciated.
TIA