这是我的函数。
如果您将MemoryStream传递给XmlReader,则有时无法验证正确的xml文件。我在内存中存储了XmlDocument对象,我想根据最终用户提供的xsd模式文件对其进行验证。
ValidateSchema1(string XMLPath, string XSDPath)
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(XMLPath);
using (MemoryStream mstream = new MemoryStream())
{
//StreamWriter writer = new StreamWriter(mstream);
xmlDocument.Save(mstream);
mstream.Seek(0, SeekOrigin.Begin);
XmlSchemaSet sc = new XmlSchemaSet();
// Add the schema to the collection.
sc.Add(null, XSDPath);
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = sc;
settings.ValidationEventHandler += ValidationCallBack;
// Create the XmlReader object.
// Not woking
XmlReader reader = XmlReader.Create(mstream, settings);
// Working
//XmlReader reader = XmlReader.Create(new StringReader(xmlDocument.InnerXml), settings);
// Working
//XmlReader reader = XmlReader.Create(XMLPath, settings);
// Parse the file.
while (reader.Read()) ;
}
}