XmlDocument 未执行验证?
我有这个函数用于根据外部模式文件验证 xml 消息:
private bool IsValidMessage(string message, XmlDocument xDoc)
{
this.valid = true;
byte[] bytes = Encoding.UTF8.GetBytes(message);
MemoryStream ms = new MemoryStream(bytes);
ms.Flush();
ms.Position = 0;
XmlReaderSettings xSettings = new XmlReaderSettings();
xSettings.ValidationType = ValidationType.Schema;
xSettings.Schemas = new System.Xml.Schema.XmlSchemaSet();
xSettings.Schemas.Add(null, "message.xsd");
xSettings.ValidationEventHandler += delegate(object sender, ValidationEventArgs e) {
this.valid = false;
ShowMessage("Wrong message format: " + message);
};
XmlReader xReader = XmlReader.Create(ms, xSettings);
xDoc.Load(xReader);
return valid;
}
当我调用 IsValidMesage("nothing", xDoc); 时它返回true,并且validationEventHandler委托中的代码永远不会执行...(加载抛出异常,但我认为应该在委托中处理它...)你知道为什么吗?
I have this function for validate xml messages against external schema file:
private bool IsValidMessage(string message, XmlDocument xDoc)
{
this.valid = true;
byte[] bytes = Encoding.UTF8.GetBytes(message);
MemoryStream ms = new MemoryStream(bytes);
ms.Flush();
ms.Position = 0;
XmlReaderSettings xSettings = new XmlReaderSettings();
xSettings.ValidationType = ValidationType.Schema;
xSettings.Schemas = new System.Xml.Schema.XmlSchemaSet();
xSettings.Schemas.Add(null, "message.xsd");
xSettings.ValidationEventHandler += delegate(object sender, ValidationEventArgs e) {
this.valid = false;
ShowMessage("Wrong message format: " + message);
};
XmlReader xReader = XmlReader.Create(ms, xSettings);
xDoc.Load(xReader);
return valid;
}
When I call IsValidMesage("nothing", xDoc); it returns true and code in validationEventHandler delegate never executes...(load throws exception but i think it should be taken care of in the delegate...) Do you have any idea why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为我找到了原因,但这只是我的猜测:
当在字符串中应该表示正确的 xml 文档只是一些字符串(例如示例中的“无”)时,验证不会发生,因为加载会抛出异常,这不是一个根本没有xml。
Think I found the reason, but this is only my guess:
When in string that should represent a proper xml document is just some string (like "nothing" in example) the validation would not happen becouse load throws exception that this isn't an xml at all.
http://msdn.microsoft.com/en-us/library/ms162371。 aspx
我认为你需要这样做:
http://msdn.microsoft.com/en-us/library/ms162371.aspx
I think you need to do: