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. php跳转页面

    1.header(location:'url'); header函数前面不能有输出 ! 可以先输出到缓存. 2js echo "<script language='javascript ...

  2. oracle用户创建

    Microsoft Windows [版本 6.1.7601]版权所有 (c) 2009 Microsoft Corporation.保留所有权利. G:\Users\Admin>sqlplus ...

  3. Nginx配置文件

    https://www.digitalocean.com/community/tutorials/understanding-the-nginx-configuration-file-structur ...

  4. Webpack中hash与chunkhash的区别,以及js与css的hash指纹解耦方案

    文件的hash指纹通常作为前端静态资源实现增量更新的方案之一,Webpack是目前最流行的开源编译工具之一,其强大的功能也带来很多坑(当然,大部分麻烦其实都可以在官方文档中找到答案). 比如,在Web ...

  5. Oracle 删除重复数据只留一条

    查询及删除重复记录的SQL语句   1.查找表中多余的重复记录,重复记录是根据单个字段(Id)来判断   select * from 表 where Id in (select Id from 表 g ...

  6. jpeg huffman coding table

    亮度DC系数的取值范围及序号:                                                               序号(size) 取值范围 0 0  1 - ...

  7. 常用shell 命令整理 一 进程 cpu

    1.查看内存从大到小排列 ps -e -o "%C : %p : %z : %a"|sort -k5 -nr 分析: -e 显示进程 -o 按用户自定义格式显示 %C cpu %p ...

  8. VS2010+Qt5.4.0 环境搭建(离线安装)

    原创作者:http://blog.csdn.net/solomon1558/article/details/44084969 前言 因项目需要Qt开发GUI,我根据网上资料及自己的经验整理了搭建vs2 ...

  9. Windows下将nginx安装为服务运行

    今天看到nginx这个小服务器软件正式版更新到了1.4.2,想玩下它.这个服务器软件虽小,但功能强大,是开源软件,有着良好的性能,被很多个人.企业,甚至大型企业所使用! 由于是在Windows下,所以 ...

  10. 转DNS DLZ +MYSQL

    关于bind的软件介绍这里就不讲解了 大家都知道是干嘛的  这里多介绍一下DLZ这个东西 大家都知道维护bind的时候 如果想新增一个zone 需要vim 编辑添加 这样.....然后bind启动后从 ...