一、验证XML文档
若要验证 XML 文档,需要构造一个 XmlReaderSettings 对象,其中包含用于验证 XML 文档的 XML 架构定义语言 (XSD) 架构。Schema是用于描述和规范XML文档的逻辑结构的一种语言,它最大的作用就是验证XML文件逻辑结构的正确性。
二、验证的类
public class XMLValidate { /// <summary> /// 辅助验证变量 /// </summary> private static bool isValidateXML = true; /// <summary> /// 验证提示 /// </summary> private static string message; /// <summary> /// 验证上传的XML文件是否是格式正确的 /// </summary> /// <param name="filename">XML文件路径</param> /// <param name="schema">XSD文件路径</param> /// <returns></returns> public static string ValidateXml(string filename, string schema) { XmlSchemaSet xsSet = new XmlSchemaSet(); try { xsSet.Add(null, schema); } catch (Exception ex) { return ex.Message; } // 定义公文模式的使用方式 XmlReaderSettings xrSetting = new XmlReaderSettings(); xrSetting.ValidationType = ValidationType.Schema; // 关联验证读取器与架构集合 xrSetting.Schemas = xsSet; // 添加发生错误时的事件处理程序 xrSetting.ValidationEventHandler += new ValidationEventHandler(MyValidationEventHandler); // 使用最新的方式来构建可进行校验的读取器并构造验证读取器 XmlReader xr = XmlReader.Create(filename, xrSetting); // 循环检测所有的文档节点 try { while (xr.Read()) {} } catch (Exception ex) { return ex.Message; } xr.Close(); return message; } /// <summary> /// 验证处理 /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private static void MyValidationEventHandler(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Warning) { message = args.Message; } else { message=args.Message; } isValidateXML = false; } }
三、把需要验证的XML文件转换成XSD文件
/// <summary> /// 确定按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSubmit_Click(object sender, EventArgs e) { string path = this.txtPath.Text; if (string.IsNullOrEmpty(path)) { MessageBox.Show("请选择文件"); return; } FileStream stream = new FileStream(path, FileMode.Open); EvidenceFilesModel dep = (EvidenceFilesModel)XMLParser.Deserialize(typeof(EvidenceFilesModel), stream); stream.Close(); string xml = XMLParser.Serializer(typeof(EvidenceFilesModel), dep); string flag = XMLValidate.ValidateXml(path, @"C:UsersPEPEDesktopig.xsd"); this.lblMsg.Text = flag; }
XML 转换成XSD工具下载,使用方法直接把XML文档拖到xsd.exe 上即可
读取字节点 linq to xml
/// <summary>
/// 证据完整性信息
/// </summary>
public IntegrityModel Validate_Integrity(XDocument xDocument)
{
//XmlReader nodeReader = XmlReader.Create(new StringReader(xml));
//XDocument xElement = XDocument.Load(nodeReader);
IEnumerable<XElement> query = from w in xDocument.Descendants("Integrity") select w;
return (IntegrityModel)IntegrityValidate.ValidateIntegrity_Integrity(query);
}