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. Python *与** 参数问题

    问题:     Python的函数定义中有两种特殊的情况,即出现*,**的形式.     如:def myfun1(username, *keys)或def myfun2(username, **ke ...

  2. (一)SQL Server分区详解Partition(目录)

    一.SQL Server分区介绍 在SQL Server中,数据库的所有表和索引都视为已分区表和索引,默认这些表和索引值包含一个分区:也就是说表或索引至少包含一个分区.SQL Server中数据是按水 ...

  3. 11i和R12配置JAR包

    R11:$IAS_ORACLE_HOME/Apache/Jserv/etc/jserv.properties R12: 方法1:直接解压JAR包放到$JAVA_TOP下: 方法2:编辑:$ORA_CO ...

  4. mac os 如何加载 Java Native/Shared Library (.jnilib)

    1 . 问题描述 今天在开发 Java 解压.z 文件的时候 需要加载 .jnilib 文件. 总是提示 Native code library failed to load. java.lang.U ...

  5. 转:入门Webpack,看这篇就够了

    写在前面的话 阅读本文之前,先看下面这个webpack的配置文件,如果每一项你都懂,那本文能带给你的收获也许就比较有限,你可以快速浏览或直接跳过:如果你和十天前的我一样,对很多选项存在着疑惑,那花一段 ...

  6. 大型App要搞的几个系统

    路由模块: 解耦各个业务,统一收敛页面跳转,动态决策跳转实现:   鉴权模块:收敛鉴权项目(比如登录.输入密码.短信验证.扫脸),后台动态控制鉴权项目:   收银台:收敛支付,统一到收银台:   开关 ...

  7. mybatis批量删除提示类型错误

    一. 这里主要考虑两种参数类型:数组或者集合. 而这点区别主要体现在EmpMapper.xml文件中标签的collection属性: 当collection="array"时,表名 ...

  8. Xml序列化去掉命名空间,去掉申明

    #region 序列化        /// <summary>        /// 序列化        /// </summary>        /// <par ...

  9. cookie的存储和获取

    在做用户登录时经常会用到cookie,如何将用户名和密码保存至cookie中呢?如何获取cookie中的数据呢? 一.用jquery.cookie.js保存数据 在页面内引入jQuery.cookie ...

  10. java中readLine()方法为什么有的行读不到?

    今天在使用java对IO操作时,readLine()输出到控制台的行少了很多.后来发现readLine()实际上是一次读取一行.如果我们不话readLine()读取的行内容赋给一个字符串的话,每直接调 ...