這是我的功能。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