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. INTRODUCTION TO BIOINFORMATICS

    INTRODUCTION TO BIOINFORMATICS      这套教程源自Youtube,算得上比较完整的生物信息学领域的视频教程,授课内容完整清晰,专题化的讲座形式,细节讲解比国内的京师大 ...

  2. (转载)android:android.content.res.Resources$NotFoundException: String resource ID #..

    android.content.res.Resources$NotFoundException: String resource ID #0x0 找不到资源文件ID #0x0 原因分析如下: 遇到这种 ...

  3. 关于unity如何制作mmo

    昨天去看了下unity的成都openday,还是有很多收获的,之前我对于这类的活动始终提不起来兴趣,不过看来日后还是要多参加下类似的活动长长见识. 公司打算开发3d mmo手游,昨天好玩123恰好也分 ...

  4. jcFeather For Arnold

    jcFeather 现在可以支持Arnold了,可以用Arnold来贴图方式渲染jcFeather的刷出的多边形羽毛. jcFeather 自带笔刷刷羽毛多边形,再配上一个Arnold shader ...

  5. nodeJS爬虫---慕课网

    源代码一(爬取html源码) //引入http模块var http = require('http');//引入url地址var url = 'http://www.imooc.com/learn/2 ...

  6. Azure上的那些IP

    相信第一次接触Azure的读者都会碰到这样一个问题,就是Azure的IP地址,笔者第一次接触Azure也是被搞懵逼了,一会儿VIP,不知道的还以为是会员的意思呢,一会儿又是DIP,后来又来了个PIP, ...

  7. EKF的理解

    若已知参考点(landmarks)的坐标,则状态向量中不必含有xL, 从而实现的仅为机器人在已知环境中的定位,求解大大减少(状态向量维度仅为运动状态).若想实现完整SLAM,必须将xL加入状态向量中. ...

  8. Idea+TestNg配置test-output输出

    说明:testNG的工程我是使用eclipse创建的,直接导入到idea中,运行test时不会生产test-output,只能在idea的控制台中查看运行结果,然后到处报告,经过不懈的百度终于找到怎么 ...

  9. C#夯实基础之接口(《CLR via C#》读书笔记)

    一. 接口的类型 接口是引用类型.因此从值类型赋值给接口是需要装箱的.如下所示: class Program { static void Main(string[] args) { ISay catS ...

  10. 用SQL SERVER取分组数据第一条:查出每个班级的成绩第一名

    create table test (id int, name ), score int, classname )); ,,'一班'); ,,'一班'); ,,'一班'); ,,'二班'); ,,'二 ...