C# 使用 XSD 文件验证 XML 文件 [英] C# validate XML file using XSD file

查看:37
本文介绍了C# 使用 XSD 文件验证 XML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 XML 文件 - 它是从解析器 这里我有一个 XSD 文件 .关键是使用 XSD 文件(来自特定路径)验证 XML 文件(来自特定路径)并返回标志(是否经过验证).我看到的大部分代码都没有使用 XSD 文件进行验证.有没有可能使用 XSD file 验证 XML 文件的方法?

I have a XML file - its generated from parser here and I have a XSD file . The key is to validate the XML file (from specific path) using the XSD file (from specific path) and return flag if it's validated or not. Most of the code I saw was without using a XSD file to validate. Is there a possible way to validate XML file using XSD file?

推荐答案

一些代码:

XmlDocument doc = new XmlDocument() ;
doc.load(xmlFileName) ;
doc.Schemas.Add("",xsdFileName);
doc.Schemas.Compile();
TheSchemaErrors   = new List<string>() ;
TheSchemaWarnings = new List<string>() ;
doc.Validate(Xml_ValidationEventHandler);
if (TheSchemaErrors  .Count>0) { // display errors  }
if (TheSchemaWarnings.Count>0) { // display warnings  }
...
private List<string> TheSchemaErrors ;
private List<string> TheSchemaWarnings ;

private void Xml_ValidationEventHandler(object sender,ValidationEventArgs e)
{
  switch (e.Severity)
  {
    case XmlSeverityType.Error   : TheSchemaErrors  .Add(e.Message) ; break;
    case XmlSeverityType.Warning : TheSchemaWarnings.Add(e.Message) ; break;
  }
}

这篇关于C# 使用 XSD 文件验证 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆