- using System;
- using System.Collections;
- using System.Data;
- using System.IO;
- using System.Xml;
- using System.Xml.Schema;
- using System.Text;
- namespace hlp
- {
- public class XMLValidator
- {
- // Validation Error Count
- private int m_ErrorsCount = 0;
- // Validation Error Message
- private string m_ErrorMessage = "";
- private void ValidationHandler(object sender,
- ValidationEventArgs args)
- {
- m_ErrorMessage = m_ErrorMessage + args.Message + "\\r\\n";
- m_ErrorsCount ++;
- }
- public bool Validate(string strXMLDoc, string strXSDPath)
- {
- try
- {
- // Declare local objects
- XmlTextReader _xmltextreader = null;
- XmlSchemaCollection _xmlschemacol = null;
- XmlValidatingReader _xmlvalidatingreader = null;
- // Text reader object
- _xmltextreader = new XmlTextReader(strXSDPath);
- _xmlschemacol = new XmlSchemaCollection();
- _xmlschemacol.Add(null, _xmltextreader);
- // XML validator object
- _xmlvalidatingreader = new XmlValidatingReader( strXMLDoc,
- XmlNodeType.Document, null);
- _xmlvalidatingreader.Schemas.Add(_xmlschemacol);
- // Add validation event handler
- _xmlvalidatingreader.ValidationType = ValidationType.Schema;
- _xmlvalidatingreader.ValidationEventHandler +=
- new ValidationEventHandler(ValidationHandler);
- // Validate XML data
- while(_xmlvalidatingreader.Read());
- _xmlvalidatingreader.Close();
- // Raise exception, if XML validation fails
- if (m_ErrorsCount > 0)
- {
- throw new Exception(m_ErrorMessage);
- }
- return true;
- }
- catch(Exception Xcp)
- {
- this.m_ErrorMessage = Xcp.Message;
- return false;
- }
- }
- public string ValidationError
- {
- get
- {
- return this.m_ErrorMessage;
- }
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/201220121097.html
来源: http://www.codesnippet.cn/detail/201220121097.html