这是我的功能。Xml架构验证失败,在C#中使用MemoryStream
如果您将MemoryStream传递给XmlReader,它有时不验证正确的xml文件。我将XmlDocument对象存储在内存中,我想根据最终用户提供的xsd Schema文件对其进行验证。
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()) ;
}
}
你确定XML是有效的验证失败时?验证例外应该告诉你_why_失败。 – Oded 2010-12-10 21:28:16