XmlValidatingReader
private void Page_Load(object sender, System.EventArgs e)
{
FileStream stream = new FileStream(Server.MapPath("people.xml"), FileMode.Open);
//创建XmlValidatingReader类的对象
XmlValidatingReader vr = new XmlValidatingReader(stream, XmlNodeType.Element, null);
//加载XML架构文档
vr.Schemas.Add(null, Server.MapPath("people.xsd"));
//说明验证的方式是根据XML架构
vr.ValidationType = ValidationType.Schema;
vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);
//对文档进行验证
while(vr.Read());
//显示验证过程完成
Page.Response.Write("<b>Validation finished!<b>");
//关闭打开的文件
stream.Close();
}
private void ValidationHandler(object sender, ValidationEventArgs args)
{
//显示验证失败的消息
Page.Response.Write("<b>Validation error: </b>" + args.Message + "<p>");
}
people.xml:
<?xml version="1.0" encoding="utf-8"?>
<PEOPLE xmlns="http://tempuri.org/people.xsd">
<PERSON>Tom</PERSON>
<PERSON>Fred</PERSON>
</PEOPLE>