现在的位置: 首页 > 综合 > 正文

.net中使用XML Schema验证

2013年10月03日 ⁄ 综合 ⁄ 共 1146字 ⁄ 字号 评论关闭

  相关的.net类
XmlReader
XmlReaderSettings
XmlSchemaSet

在.net里面验证Schema是件很容易的事 只要在XmlReader打开文件的时候填上一个 要求验证的setting就行了 建议不要在这个基础上乱封装一些XmlSchemaValidator之类的东西。

 

例子 在某个asp.net page 里面使用schema 

(语言C#  版本要求.net3.0+)

using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
 
        XmlSchemaSet sc = new XmlSchemaSet();
        // Add the schema to the collection.
        sc.Add(null, @"C:/Documents and Settings/csf/My Documents/Visual Studio 2008/WebSite2/xhtml1-transitional.xsd");
 
 
        // Set the validation settings.
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ValidationType = ValidationType.Schema;
        settings.Schemas = sc;
        settings.ProhibitDtd = false;
        settings.ValidationEventHandler += new ValidationEventHandler(delegate(object senderc, ValidationEventArgs ec) { Response.Write(ec.Message); });
 
        // Create the XmlReader object.
        XmlReader reader = XmlReader.Create(@"C:/Documents and Settings/csf/My Documents/Visual Studio 2008/WebSite2/HTMLPage2.htm", settings);
 
        // Parse the file.
        while (reader.Read()) ;
        reader.Close();
    }
}

抱歉!评论已关闭.