📄 util.cs
字号:
using System;
using System.Web;
//using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Schema;
using System.Data;
using System.IO;
/// <summary>
/// 提供公共函数和方法供整个应用程序使用
/// </summary>
public class Util
{
private static Object lockObj = new Object();
/// <summary>
/// 当xml验证发生错误时的回调函数
/// </summary>
private static void ValidationEventHandler(object sender, ValidationEventArgs e)
{
lock (lockObj)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
break;
case XmlSeverityType.Warning:
break;
}
}
}
/// <summary>
/// 验证Xml文件是否格式良好,确定配置文件。
/// </summary>
private static void ValidateXml(string xmlFilePath, string schemaFilePath)
{
//创建一个XmlSchemaSet,并且将指定路径的Schema文件添加到settings.Schemas.
XmlSchemaSet schema = new XmlSchemaSet();
schema.Add(null, schemaFilePath);
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(schema);
// 解析XML数据文件。并用指定的Sechema进行验证。
using (XmlReader reader = XmlReader.Create(xmlFilePath, settings))
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
xmlDoc.Validate(eventHandler);
}
}
/// <summary>
/// 读取xmlFilePath中的XML文件,并使用指定的方案文件进行验证。并返回包含了XML文件数据的DataSet.
/// </summary>
public static DataSet ReadAndValidateXml(string xmlFilePath, string schemaFilePath)
{
DataSet dataSet = null;
//先对该文件和Schema进行验证操作。
Util.ValidateXml(xmlFilePath, schemaFilePath);
using (FileStream fs_xml = new FileStream(xmlFilePath, FileMode.Open, FileAccess.Read))
{
using (FileStream fs_xsd = new FileStream(schemaFilePath, FileMode.Open, FileAccess.Read))
{
//调用DataSet的ReadXmlSchema方法首先读取Secham,再加载数据。
dataSet = new DataSet();
dataSet.ReadXmlSchema(fs_xsd);
dataSet.ReadXml(fs_xml, XmlReadMode.IgnoreSchema);
}
}
//返回该DataSet.
return dataSet;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -