开发者

XmlDocument not performing validation?

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;

    xSetti开发者_C百科ngs.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?


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

I think you need to do:

xmlDoc.Validate(eventhandler);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜