您的位置:首页 > 编程语言 > C#

C# Schema验证Xml的若干种方法

2012-09-05 10:58 260 查看
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Schema;
using System.Xml;
using System.IO;
namespace MyClass1
{
public class TestSchema
{
private static string Namespace = "http://www.beyondbit.com";
private static bool isValid = true;
public static bool ValidationSchema(string filename)
{
XmlTextReader r = new XmlTextReader(filename);
XmlValidatingReader v = new XmlValidatingReader(r);
v.ValidationType = ValidationType.Schema;
v.ValidationEventHandler += new ValidationEventHandler(MyValidationEventHandler);
while (v.Read())
{
// Can add code here to process the content.
}
v.Close();
return isValid;
}
public static bool ValidationSchemaNew(string filename, string schema)
{
XmlSchemaSet xsSet = new XmlSchemaSet();
try
{
xsSet.Add(Namespace, schema);
}
catch(Exception ex) {
string a = ex.Message;
return false;
}
// 定义公文模式的使用方式
XmlReaderSettings xrSetting = new XmlReaderSettings();
xrSetting.ValidationType = ValidationType.Schema;
// 关联验证读取器与架构集合
xrSetting.Schemas = xsSet;
// 添加发生错误时的事件处理程序
xrSetting.ValidationEventHandler += new ValidationEventHandler(MyValidationEventHandler);
// 使用最新的方式来构建可进行校验的读取器并构造验证读取器
XmlReader xr = XmlReader.Create(filename, xrSetting);
// 循环检测所有的文档节点
while (xr.Read())
{
}
xr.Close();
return isValid;
}
public static bool ValidationSchemaNow(string xmlstring, string schemastring)
{
//构建待验证数据的XmlReader对象
XmlReader xmlDataReader = XmlTextReader.Create(new StringReader(xmlstring));
//构建标准的XmlReader对象
XmlReader xmlSchemaReader = XmlTextReader.Create(new StringReader(schemastring));
// 定义公文模式的使用方式
XmlReaderSettings xrSetting = new XmlReaderSettings();
try
{
xrSetting.Schemas.Add(null, xmlSchemaReader);
}
catch (System.Xml.Schema.XmlSchemaException ex)
{
string b = ex.Message;
return false;
}
xrSetting.ValidationType = ValidationType.Schema;
xrSetting.ValidationEventHandler += new ValidationEventHandler(MyValidationEventHandler);
XmlReader xr = XmlReader.Create(xmlDataReader, xrSetting);
while (xr.Read())
{
}
xr.Close();
return isValid;
}
/// <summary>
/// 验证处理
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private static void MyValidationEventHandler(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
{
WriteErrorLogs("Validation Warning:   " + args.Message);
}
else
{
WriteErrorLogs("Validation Error:   " + args.Message);
}
isValid = false;
}
/// <summary>
/// 记录错误日志
/// </summary>
/// <param name="ss"></param>
private static void WriteErrorLogs(string ss)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(@"C:\test_error.txt", true, Encoding.UTF8);
sw.WriteLine("[" + DateTime.Now.ToString() + "]" + ss);
sw.Flush();
sw.Close();
}
catch { sw.Close(); }
}
}


以上方法摘自网上,下边的方法是在项目中经过实践的:

public class SchemaValidationHelper
{

public string ErrorMessage { get; set; }
public event ValidationEventHandler ValidationHandler;

public bool CheckValidate(Stream xmlStream, XmlSchemaSet xmlSchemaSet)
{
if (xmlStream.Length > 0)
{
XmlDocument doc = new XmlDocument();
xmlStream.Position = 0;
doc.Load(xmlStream);
StringBuilder sb = new StringBuilder();

ValidationEventHandler eventHandler = new ValidationEventHandler(delegate(object subSender, ValidationEventArgs subE)
{
switch (subE.Severity)
{
case XmlSeverityType.Error:
sb.Append(subE.Message);
break;
case XmlSeverityType.Warning:
break;
}
});
doc.Schemas = xmlSchemaSet;
if (ValidationHandler != null)
{
doc.Validate(ValidationHandler);
}
else
{
//Check xml
doc.Validate(eventHandler);
}
//If has error ,return false
if (sb.Length > 0)
{
ErrorMessage = sb.ToString();
return false;
}
}
else
{
return false;
}

return true;

}

}


SchemaValidationHelper validationHelper = new SchemaValidationHelper();
validationHelper.ValidationHandler+=new System.Xml.Schema.ValidationEventHandler(ValidationHelper_ValidationHandler);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: