namespace Test
{
using Microshaoft;
using System;
using System.Xml;
using System.Xml.Linq;
class Program
{
public static void Main()
{
var errors = 0;
var xsd =
@"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:element name='Root'>
<xsd:complexType>
<xsd:sequence>
<xsd:element name='Child1' minOccurs='1' maxOccurs='1'/>
<xsd:element name='Child2' minOccurs='1' maxOccurs='1'>
<xsd:complexType>
<xsd:simpleContent>
<xsd:extension base='xsd:string'>
<xsd:attribute name='Att1' default='Att1 Default Value'/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>"
;
XDocument xd = new XDocument
(
new XElement
(
"Root",
new XElement("Child1", "c1"),
new XElement("Child3", "c2"),
new XElement("Child1", "c1"),
new XElement("Child3", "c2"),
new XElement("Child3", "data3"),
new XElement("Child2", "data4"),
new XElement("Info5", "info5"),
new XElement("Info6", "info6"),
new XElement("Info7", "info7"),
new XElement("Info8", "info8")
)
);
var r = XmlValidationHelper.XsdValidateXml
(
xd
, ""
, xsd
, out errors
//, (x, y) =>
//{
// Console.WriteLine("{0}", y.Exception);
//}
);
Console.WriteLine("============== XsdValidateXml By XDocument {0}, {1} errors", r, errors);
r = XmlValidationHelper.XsdValidateXml
(
xd
, ""
, xsd
, out errors
, (x, y) =>
{
Console.WriteLine("{0}", y.Exception);
}
);
Console.WriteLine("============== XsdValidateXml By XDocument {0}, {1} errors", r, errors);
Console.WriteLine("==========================================================================");
var xml = xd.ToString();
r = XmlValidationHelper.XsdValidateXml
(
xml
, null //"http://www.contoso.com/books"
, xsd
, out errors
, false
, (x, y) =>
{
Console.WriteLine("***Validation error");
Console.WriteLine("\tSeverity:{0}", y.Severity);
Console.WriteLine("\tMessage :{0}", y.Message);
}
, (x) =>
{
Console.WriteLine("{0}", x);
return false;
}
);
Console.WriteLine("============== XsdValidateXml By Xml(XmlReader) {0}, {1} errors", r, errors);
Console.WriteLine("==========================================================================");
Console.WriteLine("press any key to continue ...");
Console.ReadLine();
xml =
@"<bookstore>
<book genre=""autobiography"" publicationdate=""1981"" ISBN=""1-861003-11-0"">
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name>Benjamin</first-name>
<last-name>Franklin</last-name>
</author>
<price>8.99</price>
</book>
<book publicationdate=""1967"" ISBN=""0-201-63361-2"">
<title>The Confidence Man</title>
<author>
<first-name>Herman</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
</book>
<book publicationdate=""1991"" ISBN=""1-861001-57-6"">
<title>The Gorgias</title>
<author>
<name>Plato</name>
</author>
<price>9.99</price>
</book>
</bookstore>
";
xsd =
@"<?xml version=""1.0"" encoding=""utf-8""?>
<xs:schema attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<!-- <xs:schema attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" targetNamespace=""http://www.contoso.com/books"" xmlns:xs=""http://www.w3.org/2001/XMLSchema""> -->
<xs:element name=""bookstore"">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs=""unbounded"" name=""book"">
<xs:complexType>
<xs:sequence>
<xs:element name=""title"" type=""xs:string"" />
<xs:element name=""author"">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs=""0"" name=""name"" type=""xs:string"" />
<xs:element minOccurs=""0"" name=""first-name"" type=""xs:string"" />
<xs:element minOccurs=""0"" name=""last-name"" type=""xs:string"" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name=""price"" type=""xs:decimal"" />
</xs:sequence>
<xs:attribute name=""genre"" type=""xs:string"" use=""required"" />
<xs:attribute name=""publicationdate"" type=""xs:unsignedShort"" use=""required"" />
<xs:attribute name=""ISBN"" type=""xs:string"" use=""required"" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
";
r = XmlValidationHelper.XsdValidateXml
(
xml
, null //"http://www.contoso.com/books"
, xsd
, out errors
//, (x, y) =>
//{
// Console.WriteLine("***Validation error");
// Console.WriteLine("\tSeverity:{0}", y.Severity);
// Console.WriteLine("\tMessage :{0}", y.Message);
//}
//, (x) =>
//{
// Console.WriteLine("{0}", x);
// return false;
//}
//, true
);
Console.WriteLine("============== XsdValidateXml By Xml(XmlReader) {0}, {1} errors", r, errors);
r = XmlValidationHelper.XsdValidateXml
(
xml
, null //"http://www.contoso.com/books"
, xsd
, out errors
, true
, (x, y) =>
{
Console.WriteLine("***Validation error");
Console.WriteLine("\tSeverity:{0}", y.Severity);
Console.WriteLine("\tMessage :{0}", y.Message);
}
, (x) =>
{
Console.WriteLine("{0}", x);
return false;
}
, (x) =>
{
Console.WriteLine("{0}", x);
return false;
}
, (x) =>
{
Console.WriteLine("{0}", x);
return false;
}
);
Console.WriteLine("============== XsdValidateXml By Xml(XmlReader) {0}, {1} errors", r, errors);
Console.WriteLine("==========================================================================");
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
r = XmlValidationHelper.XsdValidateXml
(
xmlDocument
, "" //"http://www.contoso.com/books"
, xsd
, out errors
//, (x, y) =>
//{
// Console.WriteLine("***Validation error");
// Console.WriteLine("\tSeverity:{0}", y.Severity);
// Console.WriteLine("\tException :{0}", y.Exception);
//}
);
Console.WriteLine("============== XsdValidateXml By XmlDocument {0}, {1} errors", r, errors);
r = XmlValidationHelper.XsdValidateXml
(
xmlDocument
, "" //"http://www.contoso.com/books"
, xsd
, out errors
, (x, y) =>
{
Console.WriteLine("***Validation error");
Console.WriteLine("\tSeverity:{0}", y.Severity);
Console.WriteLine("\tException :{0}", y.Exception);
}
);
Console.WriteLine("============== XsdValidateXml By XmlDocument {0}, {1} errors", r, errors);
Console.WriteLine("==========================================================================");
Console.WriteLine("Validation finished");
Console.ReadLine();
}
}
}
namespace Microshaoft
{
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
public static class XmlValidationHelper
{
public static bool XsdValidateXml
(
XDocument xDocument
, XmlSchemaSet xmlSchemaSet
, out int errors
, ValidationEventHandler validationEventHandlerAction = null
)
{
var exceptions = 0;
var r = true;
xDocument.Validate
(
xmlSchemaSet
, (x, y) =>
{
r = false;
exceptions ++;
if (validationEventHandlerAction != null)
{
validationEventHandlerAction(x, y);
}
}
, true
);
errors = exceptions;
return r;
}
public static bool XsdValidateXml
(
XDocument xDocument
, string targetNamespace
, string xsd
, out int errors
, ValidationEventHandler validationEventHandlerAction = null
)
{
XmlSchemaSet xmlSchemaSet = GetXmlSchemaSet(targetNamespace, xsd);
var r = XsdValidateXml
(
xDocument
, xmlSchemaSet
, out errors
, validationEventHandlerAction
);
return r;
}
public static bool XsdValidateXml
(
XmlDocument xmlDocument
, XmlSchemaSet xmlSchemaSet
, out int errors
, ValidationEventHandler validationEventHandlerAction = null
)
{
xmlDocument.Schemas = xmlSchemaSet;
var exceptions = 0;
var r = true;
xmlDocument.Validate
(
(x, y) =>
{
r = false;
exceptions ++;
if (validationEventHandlerAction != null)
{
validationEventHandlerAction(x, y);
}
}
);
errors = exceptions;
return r;
}
public static bool XsdValidateXml
(
XmlDocument xmlDocument
, string targetNamespace
, string xsd
, out int errors
, ValidationEventHandler validationEventHandlerAction = null
)
{
var xmlSchemaSet = GetXmlSchemaSet(targetNamespace, xsd);
var r = XsdValidateXml
(
xmlDocument
, xmlSchemaSet
, out errors
, validationEventHandlerAction
);
return r;
}
public static bool XsdValidateXml
(
string xml
, out int errors
, XmlReaderSettings xmlReaderValidationSettings
, bool caughtExceptionOnlyOnce = false
, ValidationEventHandler validationEventHandlerAction = null
, Func<XmlSchemaValidationException, bool> onCaughtXmlSchemaValidationExceptionProcessFunc = null
, Func<XmlSchemaException, bool> onCaughtXmlSchemaExceptionProcessFunc = null
, Func<Exception, bool> onCaughtExceptionProcessFunc = null
)
{
var r = true;
bool reThrow = false;
var exceptions = 0;
using (var stringReader = new StringReader(xml))
{
using (var xmlReader = XmlReader.Create(stringReader, xmlReaderValidationSettings))
{
if (validationEventHandlerAction != null)
{
xmlReaderValidationSettings.ValidationEventHandler += validationEventHandlerAction;
}
bool readed = false;
var func = new Func<bool>
(
() =>
{
try
{
readed = xmlReader.Read();
}
catch (XmlSchemaValidationException xsve)
{
r = false;
exceptions ++;
if (onCaughtXmlSchemaValidationExceptionProcessFunc != null)
{
reThrow = onCaughtXmlSchemaValidationExceptionProcessFunc(xsve);
}
if (reThrow)
{
//xsve = new XmlSchemaValidationException("ReThrowInnerException", xsve);
//throw xsve;
throw;
}
if (caughtExceptionOnlyOnce)
{
readed = false;
}
}
catch (XmlSchemaException xsve)
{
r = false;
exceptions ++;
if (onCaughtXmlSchemaExceptionProcessFunc != null)
{
reThrow = onCaughtXmlSchemaExceptionProcessFunc(xsve);
}
if (reThrow)
{
//xsve = new XmlSchemaException("ReThrowInnerException", xsve);
//throw xsve;
throw;
}
if (caughtExceptionOnlyOnce)
{
readed = false;
}
}
catch (Exception e)
{
r = false;
exceptions ++;
if (onCaughtExceptionProcessFunc != null)
{
reThrow = onCaughtExceptionProcessFunc(e);
}
if (reThrow)
{
//xsve = new XmlSchemaValidationException("ReThrowInnerException", xsve);
//throw xsve;
throw;
}
if (caughtExceptionOnlyOnce)
{
readed = false;
}
}
return readed;
}
);
while
(
func()
) ;
errors = exceptions;
}
}
return r;
}
public static bool XsdValidateXml
(
string xml
, string targetNamespace
, string xsd
, out int errors
, bool caughtExceptionOnlyOnce = false
, ValidationEventHandler validationEventHandlerAction = null
, Func<XmlSchemaValidationException, bool> onCaughtXmlSchemaValidationExceptionProcessFunc = null
, Func<XmlSchemaException, bool> onCaughtXmlSchemaExceptionProcessFunc = null
, Func<Exception, bool> onCaughtExceptionProcessFunc = null
)
{
XmlReaderSettings xmlReaderSettings = GetXmlReaderValidationSettings(targetNamespace, xsd);
var r = XsdValidateXml
(
xml
, out errors
, xmlReaderSettings
, caughtExceptionOnlyOnce
, validationEventHandlerAction
, onCaughtXmlSchemaValidationExceptionProcessFunc
, onCaughtXmlSchemaExceptionProcessFunc
, onCaughtExceptionProcessFunc
);
return r;
}
public static XmlReaderSettings GetXmlReaderValidationSettings
(
string targetNamespace
, string xsd
, ValidationType validationType = ValidationType.Schema
, XmlSchemaValidationFlags xmlSchemaValidationFlags =
XmlSchemaValidationFlags.AllowXmlAttributes
| XmlSchemaValidationFlags.AllowXmlAttributes
| XmlSchemaValidationFlags.ProcessIdentityConstraints
| XmlSchemaValidationFlags.ProcessInlineSchema
| XmlSchemaValidationFlags.ProcessSchemaLocation
| XmlSchemaValidationFlags.ReportValidationWarnings
, ValidationEventHandler validationEventHandlerAction = null
)
{
XmlSchemaSet xmlSchemaSet = GetXmlSchemaSet(targetNamespace, xsd);
XmlReaderSettings xmlReaderValidationSettings = new XmlReaderSettings();
xmlReaderValidationSettings.ValidationType = validationType;
xmlReaderValidationSettings.ValidationFlags = xmlSchemaValidationFlags;
xmlReaderValidationSettings.Schemas.Add(xmlSchemaSet);
if (validationEventHandlerAction != null)
{
xmlReaderValidationSettings.ValidationEventHandler += validationEventHandlerAction;
}
return xmlReaderValidationSettings;
}
public static XmlSchemaSet GetXmlSchemaSet(string targetNamespace, string xsd)
{
using (var stringReader = new StringReader(xsd))
{
using (var xmlReader = XmlReader.Create(stringReader))
{
XmlSchemaSet xmlSchemaSet = new XmlSchemaSet();
xmlSchemaSet.Add(targetNamespace, xmlReader);
return xmlSchemaSet;
}
}
}
}
}

XmlValidationHelper XSD、Schema(XmlSchemaSet)、XmlReader(XmlValidationSettings)、XmlDocument、XDocument Validate的更多相关文章

  1. saiku、mondrian前奏之——立方体、维度、Schema的基本概念

    以前介绍了几个基本工具:saiku 和 Schema Workbench,算是入门级别的了解多维报表,如果要继续深入,需要深入了解如下几个概念: 1.OLAP 联机分析处理,和他对应的是OLTP(联机 ...

  2. xml语法、DTD约束xml、Schema约束xml、DOM解析xml

    今日大纲 1.什么是xml.xml的作用 2.xml的语法 3.DTD约束xml 4.Schema约束xml 5.DOM解析xml 1.什么是xml.xml的作用 1.1.xml介绍 在前面学习的ht ...

  3. 16.XML语法、CDATA、约束(DTD、Schema)讲解

    xml主要用来描述数据,比如配置文件,网络之间传输数据等,并且在android中也经常用xml来布局,,接下来便来学习xml常用的东西 1.XML语法 xml语法分为: 1.1 文档声明 必须位于文档 ...

  4. 【JAVA与XML、dtd约束、Schema约束】

    一.XML. (1)XML:Extensible Markup Language (2)XML是一种标记语言. (3)XML的设计宗旨是传输数据,而不是显示数据. (4)XML标签没有被预定义,即使用 ...

  5. Solr系列三:solr索引详解(Schema介绍、字段定义详解、Schema API 介绍)

    一.Schema介绍 1. Schema 是什么? Schema:模式,是集合/内核中字段的定义,让solr知道集合/内核包含哪些字段.字段的数据类型.字段该索引存储. 2. Schema 的定义方式 ...

  6. 69、schema的相关方法

    public class SObjectSchema { public void testSchema(){ //获取SObject的token //1.先获取所有token,然后通过key获取需要的 ...

  7. 68、Schema的相关类

    public class SObjectSchema { public void testSchema(){ //获取SObject的token //1.先获取所有token,然后通过key获取需要的 ...

  8. Dubbo与Zookeeper、SpringMVC整合和使用(负载均衡、容错)(略有修改)

    对应项目的代码地址为:https://github.com/liuxiaoming7708/springboot-dubbo-parent Dubbo与Zookeeper.SpringMVC整合和使用 ...

  9. JAVAEE——宜立方商城08:Zookeeper+SolrCloud集群搭建、搜索功能切换到集群版、Activemq消息队列搭建与使用

    1. 学习计划 1.solr集群搭建 2.使用solrj管理solr集群 3.把搜索功能切换到集群版 4.添加商品同步索引库. a) Activemq b) 发送消息 c) 接收消息 2. 什么是So ...

随机推荐

  1. 使用QQ第三方登录时,手机应用和网站应用对同一个QQ号,获取到的openid不一样

    使用QQ第三方登录时,手机应用和网站应用对同一个QQ号,获取到的openid不一样openid生成是根据应用的appid和QQ号的一些信息加密生成,对于一个appid和QQ号来说,openid是唯一的 ...

  2. .NET 的 WebSocket 开发包比较(转)

    .NET 的 WebSocket 开发包比较 编者按 本文出现在第三方产品评论部分中.在这一部分的文章只提供给会员,不允许工具供应商用来以任何方式和形式来促销或宣传产品.请会员报告任何垃圾信息或广告. ...

  3. Spring标签<mvc:annotation-driven/>解读

    一.AnnotationDrivenBeanDefinitionParser 通常如果我们希望通过注解的方式来进行Spring MVC开发,我们都会在***-servlet.xml中加入<mvc ...

  4. Qt 5.0+ 中 connect 新语法与重载函数不兼容问题的解决方法,以及个人看法

    Qt 5.0+ 版本提供了 connect 的新语法,相比之前的语法新语法可以提供编译期检查,使用也更方便.可是使用过程中发现一个小问题——当某个 signal 和成员函数是重载关系的时候,qmake ...

  5. knn-伪代码与实现过程

    knn特点 优点:精度高,对异常值不明感,无数据输入嘉定 缺点:计算复杂度高,空间复杂度高 适用范围:数值型和标称型 knn算法的伪代码 1.计算已知类别数据集中的点与当前之间的距离 2.按照距离递增 ...

  6. Toad各版本所包含的组件

    Toad for Oracle Base Edition Toad for Oracle Knowledge Xpert for PL/SQL Knowledge Xpert for Oracle A ...

  7. Python 局部变量与全局变量

    本来以为 局部变量就是在函数/def/class/lambda内部的变量,全局变量就是在之前这些之外的变量.但是,再一次学习Python atm 中应用时发现了一次特例(意外) 字典中 在函数内部改变 ...

  8. Python学习笔记—Python基础1 介绍、发展史、安装、基本语法

    第一周学习笔记: 一.Python介绍      1.Python的创始人为吉多·范罗苏姆.1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC语言 ...

  9. markdown语法与使用

    Markdown是一种可以使用普通文本编辑器编写的标记语言,通过简单的标记语法,它可以使普通文本内容具有一定的格式. 语法 # 文本 =>h1标签 ##文本 =>h2标签 *文本* =&g ...

  10. The specified module could not be found

    打开IIS 信息服务,在左侧找到自己的计算机,点右键,选择属性,在主属性中选编辑,打开“目录安全性”选项卡,单击“匿名访问和验证控制”里的“编辑”按钮,在弹出的对话框中确保只选中了“匿名访问”和“集成 ...