对XML文档进行Schema校验的方法(适用于Framework2.0及以上版本)

来源:互联网 发布:jsp 443端口 编辑:程序博客网 时间:2024/05/16 09:00

// 函数功能:根据已有的公文XMLSchema对公文进行检测

        // 参数含义:strArchXMLFilePath(公文XML文档路径)

        public static bool CheckArchXMLContent(string strArchXMLFilePath, out string strErrorMsg)

        {

            bool bResult = true;

            strErrorMsg = "";

            try

            {

                // 初始化出错信息

                m_strErrorMsg = "";

                string strXsdFilePath = "Example.xsd";   // xsd架构文档

                // 构造Schema架构缓存

                XmlSchemaSet xssArchContent = new XmlSchemaSet();  

                // 添加架构文件,前面是命名空间,没有为空

                xssArchContent.Add("", strXsdFilePath);

                // 定义公文模式的使用方式

                XmlReaderSettings xrsArchContent = new XmlReaderSettings();

                xrsArchContent.ValidationType = ValidationType.Schema;

                // 关联验证读取器与架构集合

                xrsArchContent.Schemas = xssArchContent;

                // 添加发生错误时的事件处理程序

                xrsArchContent.ValidationEventHandler += new ValidationEventHandler(DealError);

                // 使用最新的方式来构建可进行校验的读取器并构造验证读取器

                XmlReader xrArchContent = XmlReader.Create(strArchXMLFilePath, xrsArchContent);

                // 循环检测所有的文档节点

                while (xrArchContent.Read())

                {

                }

                // 判断是否节点有语法错误

                if (m_strErrorMsg != "")

                {

                    bResult = false;

                    strErrorMsg = m_strErrorMsg;

                }

            }

            catch (Exception e)

            {

                strErrorMsg = e.Message.ToString();

                bResult = false;

            }

            return bResult;

        }

        // 函数功能:错误处理程序

        public static void DealError(object sender, ValidationEventArgs args)

        {

            // 处理内容

            m_strErrorMsg += args.Message.ToString() + "/r/n/r/n";

        }

原创粉丝点击