【发布时间】:2011-05-23 17:49:32
【问题描述】:
这是我的功能。
如果您将 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 有效吗?验证异常应该告诉您为什么它失败了。
标签: c# xml validation xsd