翻阅了很多资料,一直没找到使用dtd进行xml验证的相关例程。
SDK Document里的帮助也不是很详细,对dtd验证的几个关键点
没有指出。经过自己的不断尝试,大致搞清了验证的方法。把
资料简单发布上来,以备参考。
<%@Page Language="C#" Debug="true"%>
<%@Import Namespace="System.Xml"%>
<%@Import Namespace="System.Xml.Schema"%>
<script Language="C#" runat="server">
XmlTextReader reader;
XmlValidatingReader vReader;
void Page_Load(object sender,EventArgs E)
{
XmlParserContext context;
reader=new XmlTextReader(Server.MapPath("test.xml"));
reader.MoveToContent();
context=new XmlParserContext(null,null,"root",null,null,"<!ELEMENT root (items)><!ELEMENT items (item)><!ELEMENT item
(#PCDATA)>",null,null,XmlSpace.None);
vReader=new XmlValidatingReader(reader.ReadOuterXml(),XmlNodeType.Element,context);
vReader.ValidationEventHandler+=new ValidationEventHandler(this.ValidationCallback);
reader=(XmlTextReader)vReader.Reader;
try{
while(vReader.Read()){}
}
catch
{
Response.Write("Important Error");
}
if (reader!=null) reader.Close();
if (vReader!=null) vReader.Close();
}
public void ValidationCallback(object Sender,ValidationEventArgs e)
{
Response.Write("Validation Error!");
Response.Write("<br>");
Response.Write("Line:"+reader.LineNumber);
Response.Write("<br>");
Response.Write("Line:"+reader.LinePosition);
}
</script>