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. 深入分析HTTP状态码502(nginx+php-fpm)

    我们的一个web项目,由于新上城市增多,导致访问量增大,DB压力增大,作为提供接口的业务方,最近被下游反馈大量请求"502". 502,bad gateway,一般都是upstre ...

  2. 怎么把本地项目和远程git仓库相连通

    1. 打开在你的项目文件夹,输入下面的命令 git init 输完上面的命令,文件夹中会出现一个.git文件夹,如下图所示,其他的的文件也会出现蓝色小问号的标志 2. 添加所有文件 git add . ...

  3. HTTP 错误 404.3 – Not Found 由于扩展配置问题而无法提供您请求的页面。如果该页面是脚本,请添加处理程序。如果应下载文件,请添加 MIME 映射。

    今天,在vs2013中新建了一个placard.json文件,当我用jq读取它的时候,去提示404,直接在浏览器访问这个文件,提示: HTTP 错误 404.3 – Not Found 由于扩展配置问 ...

  4. VirtualBox COM对象获取失败

    问题描述: Failed to instantiate CLSID_VirtualBox w/ IVirtualBox, but CLSID_VirtualBox w/ IUnknown works. ...

  5. 盘点8种CSS实现垂直居中水平居中的绝对定位居中技术

    Ⅰ.绝对定位居中(Absolute Centering)技术 我们经常用margin:0 auto来实现水平居中,而一直认为margin:auto不能实现垂直居中--实际上,实现垂直居中仅需要声明元素 ...

  6. java中File类的getPath(),getAbsolutePath(),getCanonicalPath()区别

    File file = new File(".\\test.txt"); System.out.println(file.getPath()); System.out.printl ...

  7. Mac OS X 中一些常用的命令行技巧

    一.网络设置相关 1.网卡的物理地址的动态重置 出于某些需求,例如网络中的 IP 地址或网络帐号与网卡物理地址绑定,使得多个设备无法切换上网,可尝试临时更改物理地址.不过,系统偏好设置是不能修改网卡物 ...

  8. mysql的enum和set数据类型

    定义一个ENUM或者SET类型,可以约束存入的数值. ENUM中的值必须是定义过数值列中的一个,比如ENUM('a','b','c'),存入的只能是'a'或者'b'或者'c',如果存入'','d'或者 ...

  9. Microsoft QAS架接项目

    1,p位置玩文件后.运行程序命令是: QCSQueryLabelWithLES.exe -c %CD%\FinalQASModelDir --variant AMyMovie --outputFull ...

  10. R语言常用函数

    统计: mean:平均数sd:Standard Deviation 标准差var:方差median:中位数cov:协方差cor:相关系数 #环境ls/objectsrmhelp() library() ...