下面是改的书上的一个类,用XmlValidatingReader来验证XML的,按书上说的ValidationType设为Auto,可以验证DTD,XDR和XSD,我用XmlSpy测试好了三个文档,分别是DTD,XDR和XSD,以及对应的XML文件。用这家伙一测试,出了一堆错误,ValidationType的几个枚举都试了,没一个不出错的,我晕public class Validator
{
bool valid;
string msg;
string _xmlFilePath;
XmlTextReader xmlReader = null;
XmlValidatingReader vReader = null; public string Validate(string xmlFilePath, XmlSchemaCollection schemaCol)
{
valid = true;
_xmlFilePath = xmlFilePath; try
{
xmlReader = new XmlTextReader(_xmlFilePath);
vReader = new XmlValidatingReader(xmlReader); if (schemaCol != null)
{
vReader.Schemas.Add(schemaCol);
} vReader.ValidationType = ValidationType.Auto;
vReader.ValidationEventHandler += new ValidationEventHandler(this.ValidationCallBack); while (vReader.Read()){}
}
catch (Exception e)
{
msg += e.Message;
valid = false;
}
finally
{
if (xmlReader.ReadState != ReadState.Closed)
{
xmlReader.Close();
}
if (vReader.ReadState != ReadState.Closed)
{
vReader.Close();
}
} if (valid)
msg = "恭喜,已经通过验证!"; return msg;

} private void ValidationCallBack(object sender, ValidationEventArgs args)
{
valid = false;
DateTime today = DateTime.Now;
msg += "出错文件:" + _xmlFilePath + "<br>";
msg += args.Message + "<br>" + "<i>" + today.ToString() + "</i>";
if (xmlReader.LineNumber > 0)
msg += " <i>行: " + xmlReader.LineNumber + " 列: " + xmlReader.LinePosition + "</i><br>";
msg += string.Empty.PadLeft(30, '#') + "<br>";
} } //Validatortest.aspx中:private void Button1_Click(object sender, System.EventArgs e)
{
if (this.fXml.PostedFile.ContentLength <= 0)
return;
if (this.fSchema.PostedFile.ContentLength <=0)
return; int tmp;
string folderPath = Server.MapPath("data");

tmp = fXml.Value.LastIndexOf(@"\");
string xmlPath = folderPath + fXml.Value.Substring(tmp);
this.fXml.PostedFile.SaveAs(xmlPath);

tmp = fSchema.Value.LastIndexOf(@"\");
string schemaPath = folderPath + fSchema.Value.Substring(tmp);
this.fSchema.PostedFile.SaveAs(schemaPath);
XmlSchemaCollection schemaCol = new XmlSchemaCollection();

try
{
XmlSchema s = new XmlSchema();
s.SourceUri = schemaPath;
schemaCol.Add(s);
}
catch (Exception ex)
{
this.Label1.Text = ex.Message;
return;
} Validator v = new Validator();
v.Validate(xmlPath, schemaCol); this.Label1.Text = v.Validate(xmlPath, schemaCol);
}测试后信息如下:出错文件:E:\asp.net\xml\data\01.xml
未声明“ContactMenList”元素。 file:///E:/asp.net/xml/data/01.xml, (2, 2)处发生了错误。
2003-12-19 13:22:30 行: 2 列: 2
##############################
出错文件:E:\asp.net\xml\data\01.xml
未声明“ContactMen”元素。 file:///E:/asp.net/xml/data/01.xml, (3, 3)处发生了错误。
2003-12-19 13:22:30 行: 3 列: 3
##############################
...
...
...
所有元素都出错了...