1.  
  2. namespace Test
  3. {
  4. using Microshaoft;
  5. using System;
  6. using System.Xml;
  7. using System.Xml.Linq;
  8. class Program
  9. {
  10. public static void Main()
  11. {
  12. var errors = 0;
  13. var xsd =
  14. @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
  15. <xsd:element name='Root'>
  16. <xsd:complexType>
  17. <xsd:sequence>
  18. <xsd:element name='Child1' minOccurs='1' maxOccurs='1'/>
  19. <xsd:element name='Child2' minOccurs='1' maxOccurs='1'>
  20. <xsd:complexType>
  21. <xsd:simpleContent>
  22. <xsd:extension base='xsd:string'>
  23. <xsd:attribute name='Att1' default='Att1 Default Value'/>
  24. </xsd:extension>
  25. </xsd:simpleContent>
  26. </xsd:complexType>
  27. </xsd:element>
  28. </xsd:sequence>
  29. </xsd:complexType>
  30. </xsd:element>
  31. </xsd:schema>"
  32. ;
  33. XDocument xd = new XDocument
  34. (
  35. new XElement
  36. (
  37. "Root",
  38. new XElement("Child1", "c1"),
  39. new XElement("Child3", "c2"),
  40. new XElement("Child1", "c1"),
  41. new XElement("Child3", "c2"),
  42. new XElement("Child3", "data3"),
  43. new XElement("Child2", "data4"),
  44. new XElement("Info5", "info5"),
  45. new XElement("Info6", "info6"),
  46. new XElement("Info7", "info7"),
  47. new XElement("Info8", "info8")
  48. )
  49. );
  50. var r = XmlValidationHelper.XsdValidateXml
  51. (
  52. xd
  53. , ""
  54. , xsd
  55. , out errors
  56. //, (x, y) =>
  57. //{
  58. // Console.WriteLine("{0}", y.Exception);
  59. //}
  60. );
  61. Console.WriteLine("============== XsdValidateXml By XDocument {0}, {1} errors", r, errors);
  62. r = XmlValidationHelper.XsdValidateXml
  63. (
  64. xd
  65. , ""
  66. , xsd
  67. , out errors
  68. , (x, y) =>
  69. {
  70. Console.WriteLine("{0}", y.Exception);
  71. }
  72. );
  73. Console.WriteLine("============== XsdValidateXml By XDocument {0}, {1} errors", r, errors);
  74. Console.WriteLine("==========================================================================");
  75. var xml = xd.ToString();
  76. r = XmlValidationHelper.XsdValidateXml
  77. (
  78. xml
  79. , null //"http://www.contoso.com/books"
  80. , xsd
  81. , out errors
  82. , false
  83. , (x, y) =>
  84. {
  85. Console.WriteLine("***Validation error");
  86. Console.WriteLine("\tSeverity:{0}", y.Severity);
  87. Console.WriteLine("\tMessage :{0}", y.Message);
  88. }
  89. , (x) =>
  90. {
  91. Console.WriteLine("{0}", x);
  92. return false;
  93. }
  94. );
  95. Console.WriteLine("============== XsdValidateXml By Xml(XmlReader) {0}, {1} errors", r, errors);
  96. Console.WriteLine("==========================================================================");
  97. Console.WriteLine("press any key to continue ...");
  98. Console.ReadLine();
  99. xml =
  100. @"<bookstore>
  101. <book genre=""autobiography"" publicationdate=""1981"" ISBN=""1-861003-11-0"">
  102. <title>The Autobiography of Benjamin Franklin</title>
  103. <author>
  104. <first-name>Benjamin</first-name>
  105. <last-name>Franklin</last-name>
  106. </author>
  107. <price>8.99</price>
  108. </book>
  109. <book publicationdate=""1967"" ISBN=""0-201-63361-2"">
  110. <title>The Confidence Man</title>
  111. <author>
  112. <first-name>Herman</first-name>
  113. <last-name>Melville</last-name>
  114. </author>
  115. <price>11.99</price>
  116. </book>
  117. <book publicationdate=""1991"" ISBN=""1-861001-57-6"">
  118. <title>The Gorgias</title>
  119. <author>
  120. <name>Plato</name>
  121. </author>
  122. <price>9.99</price>
  123. </book>
  124. </bookstore>
  125. ";
  126. xsd =
  127. @"<?xml version=""1.0"" encoding=""utf-8""?>
  128. <xs:schema attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
  129. <!-- <xs:schema attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" targetNamespace=""http://www.contoso.com/books"" xmlns:xs=""http://www.w3.org/2001/XMLSchema""> -->
  130. <xs:element name=""bookstore"">
  131. <xs:complexType>
  132. <xs:sequence>
  133. <xs:element maxOccurs=""unbounded"" name=""book"">
  134. <xs:complexType>
  135. <xs:sequence>
  136. <xs:element name=""title"" type=""xs:string"" />
  137. <xs:element name=""author"">
  138. <xs:complexType>
  139. <xs:sequence>
  140. <xs:element minOccurs=""0"" name=""name"" type=""xs:string"" />
  141. <xs:element minOccurs=""0"" name=""first-name"" type=""xs:string"" />
  142. <xs:element minOccurs=""0"" name=""last-name"" type=""xs:string"" />
  143. </xs:sequence>
  144. </xs:complexType>
  145. </xs:element>
  146. <xs:element name=""price"" type=""xs:decimal"" />
  147. </xs:sequence>
  148. <xs:attribute name=""genre"" type=""xs:string"" use=""required"" />
  149. <xs:attribute name=""publicationdate"" type=""xs:unsignedShort"" use=""required"" />
  150. <xs:attribute name=""ISBN"" type=""xs:string"" use=""required"" />
  151. </xs:complexType>
  152. </xs:element>
  153. </xs:sequence>
  154. </xs:complexType>
  155. </xs:element>
  156. </xs:schema>
  157. ";
  158. r = XmlValidationHelper.XsdValidateXml
  159. (
  160. xml
  161. , null //"http://www.contoso.com/books"
  162. , xsd
  163. , out errors
  164. //, (x, y) =>
  165. //{
  166. // Console.WriteLine("***Validation error");
  167. // Console.WriteLine("\tSeverity:{0}", y.Severity);
  168. // Console.WriteLine("\tMessage :{0}", y.Message);
  169. //}
  170. //, (x) =>
  171. //{
  172. // Console.WriteLine("{0}", x);
  173. // return false;
  174. //}
  175. //, true
  176. );
  177. Console.WriteLine("============== XsdValidateXml By Xml(XmlReader) {0}, {1} errors", r, errors);
  178. r = XmlValidationHelper.XsdValidateXml
  179. (
  180. xml
  181. , null //"http://www.contoso.com/books"
  182. , xsd
  183. , out errors
  184. , true
  185. , (x, y) =>
  186. {
  187. Console.WriteLine("***Validation error");
  188. Console.WriteLine("\tSeverity:{0}", y.Severity);
  189. Console.WriteLine("\tMessage :{0}", y.Message);
  190. }
  191. , (x) =>
  192. {
  193. Console.WriteLine("{0}", x);
  194. return false;
  195. }
  196. , (x) =>
  197. {
  198. Console.WriteLine("{0}", x);
  199. return false;
  200. }
  201. , (x) =>
  202. {
  203. Console.WriteLine("{0}", x);
  204. return false;
  205. }
  206. );
  207. Console.WriteLine("============== XsdValidateXml By Xml(XmlReader) {0}, {1} errors", r, errors);
  208. Console.WriteLine("==========================================================================");
  209. XmlDocument xmlDocument = new XmlDocument();
  210. xmlDocument.LoadXml(xml);
  211. r = XmlValidationHelper.XsdValidateXml
  212. (
  213. xmlDocument
  214. , "" //"http://www.contoso.com/books"
  215. , xsd
  216. , out errors
  217. //, (x, y) =>
  218. //{
  219. // Console.WriteLine("***Validation error");
  220. // Console.WriteLine("\tSeverity:{0}", y.Severity);
  221. // Console.WriteLine("\tException :{0}", y.Exception);
  222. //}
  223. );
  224. Console.WriteLine("============== XsdValidateXml By XmlDocument {0}, {1} errors", r, errors);
  225. r = XmlValidationHelper.XsdValidateXml
  226. (
  227. xmlDocument
  228. , "" //"http://www.contoso.com/books"
  229. , xsd
  230. , out errors
  231. , (x, y) =>
  232. {
  233. Console.WriteLine("***Validation error");
  234. Console.WriteLine("\tSeverity:{0}", y.Severity);
  235. Console.WriteLine("\tException :{0}", y.Exception);
  236. }
  237. );
  238. Console.WriteLine("============== XsdValidateXml By XmlDocument {0}, {1} errors", r, errors);
  239. Console.WriteLine("==========================================================================");
  240. Console.WriteLine("Validation finished");
  241. Console.ReadLine();
  242. }
  243. }
  244. }
  245. namespace Microshaoft
  246. {
  247. using System;
  248. using System.IO;
  249. using System.Xml;
  250. using System.Xml.Linq;
  251. using System.Xml.Schema;
  252. public static class XmlValidationHelper
  253. {
  254. public static bool XsdValidateXml
  255. (
  256. XDocument xDocument
  257. , XmlSchemaSet xmlSchemaSet
  258. , out int errors
  259. , ValidationEventHandler validationEventHandlerAction = null
  260. )
  261. {
  262. var exceptions = 0;
  263. var r = true;
  264. xDocument.Validate
  265. (
  266. xmlSchemaSet
  267. , (x, y) =>
  268. {
  269. r = false;
  270. exceptions ++;
  271. if (validationEventHandlerAction != null)
  272. {
  273. validationEventHandlerAction(x, y);
  274. }
  275. }
  276. , true
  277. );
  278. errors = exceptions;
  279. return r;
  280. }
  281. public static bool XsdValidateXml
  282. (
  283. XDocument xDocument
  284. , string targetNamespace
  285. , string xsd
  286. , out int errors
  287. , ValidationEventHandler validationEventHandlerAction = null
  288. )
  289. {
  290. XmlSchemaSet xmlSchemaSet = GetXmlSchemaSet(targetNamespace, xsd);
  291. var r = XsdValidateXml
  292. (
  293. xDocument
  294. , xmlSchemaSet
  295. , out errors
  296. , validationEventHandlerAction
  297. );
  298. return r;
  299. }
  300. public static bool XsdValidateXml
  301. (
  302. XmlDocument xmlDocument
  303. , XmlSchemaSet xmlSchemaSet
  304. , out int errors
  305. , ValidationEventHandler validationEventHandlerAction = null
  306. )
  307. {
  308. xmlDocument.Schemas = xmlSchemaSet;
  309. var exceptions = 0;
  310. var r = true;
  311. xmlDocument.Validate
  312. (
  313. (x, y) =>
  314. {
  315. r = false;
  316. exceptions ++;
  317. if (validationEventHandlerAction != null)
  318. {
  319. validationEventHandlerAction(x, y);
  320. }
  321. }
  322. );
  323. errors = exceptions;
  324. return r;
  325. }
  326. public static bool XsdValidateXml
  327. (
  328. XmlDocument xmlDocument
  329. , string targetNamespace
  330. , string xsd
  331. , out int errors
  332. , ValidationEventHandler validationEventHandlerAction = null
  333. )
  334. {
  335. var xmlSchemaSet = GetXmlSchemaSet(targetNamespace, xsd);
  336. var r = XsdValidateXml
  337. (
  338. xmlDocument
  339. , xmlSchemaSet
  340. , out errors
  341. , validationEventHandlerAction
  342. );
  343. return r;
  344. }
  345. public static bool XsdValidateXml
  346. (
  347. string xml
  348. , out int errors
  349. , XmlReaderSettings xmlReaderValidationSettings
  350. , bool caughtExceptionOnlyOnce = false
  351. , ValidationEventHandler validationEventHandlerAction = null
  352. , Func<XmlSchemaValidationException, bool> onCaughtXmlSchemaValidationExceptionProcessFunc = null
  353. , Func<XmlSchemaException, bool> onCaughtXmlSchemaExceptionProcessFunc = null
  354. , Func<Exception, bool> onCaughtExceptionProcessFunc = null
  355. )
  356. {
  357. var r = true;
  358. bool reThrow = false;
  359. var exceptions = 0;
  360. using (var stringReader = new StringReader(xml))
  361. {
  362. using (var xmlReader = XmlReader.Create(stringReader, xmlReaderValidationSettings))
  363. {
  364. if (validationEventHandlerAction != null)
  365. {
  366. xmlReaderValidationSettings.ValidationEventHandler += validationEventHandlerAction;
  367. }
  368. bool readed = false;
  369. var func = new Func<bool>
  370. (
  371. () =>
  372. {
  373. try
  374. {
  375. readed = xmlReader.Read();
  376. }
  377. catch (XmlSchemaValidationException xsve)
  378. {
  379. r = false;
  380. exceptions ++;
  381. if (onCaughtXmlSchemaValidationExceptionProcessFunc != null)
  382. {
  383. reThrow = onCaughtXmlSchemaValidationExceptionProcessFunc(xsve);
  384. }
  385. if (reThrow)
  386. {
  387. //xsve = new XmlSchemaValidationException("ReThrowInnerException", xsve);
  388. //throw xsve;
  389. throw;
  390. }
  391. if (caughtExceptionOnlyOnce)
  392. {
  393. readed = false;
  394. }
  395. }
  396. catch (XmlSchemaException xsve)
  397. {
  398. r = false;
  399. exceptions ++;
  400. if (onCaughtXmlSchemaExceptionProcessFunc != null)
  401. {
  402. reThrow = onCaughtXmlSchemaExceptionProcessFunc(xsve);
  403. }
  404. if (reThrow)
  405. {
  406. //xsve = new XmlSchemaException("ReThrowInnerException", xsve);
  407. //throw xsve;
  408. throw;
  409. }
  410. if (caughtExceptionOnlyOnce)
  411. {
  412. readed = false;
  413. }
  414. }
  415. catch (Exception e)
  416. {
  417. r = false;
  418. exceptions ++;
  419. if (onCaughtExceptionProcessFunc != null)
  420. {
  421. reThrow = onCaughtExceptionProcessFunc(e);
  422. }
  423. if (reThrow)
  424. {
  425. //xsve = new XmlSchemaValidationException("ReThrowInnerException", xsve);
  426. //throw xsve;
  427. throw;
  428. }
  429. if (caughtExceptionOnlyOnce)
  430. {
  431. readed = false;
  432. }
  433. }
  434. return readed;
  435. }
  436. );
  437. while
  438. (
  439. func()
  440. ) ;
  441. errors = exceptions;
  442. }
  443. }
  444. return r;
  445. }
  446. public static bool XsdValidateXml
  447. (
  448. string xml
  449. , string targetNamespace
  450. , string xsd
  451. , out int errors
  452. , bool caughtExceptionOnlyOnce = false
  453. , ValidationEventHandler validationEventHandlerAction = null
  454. , Func<XmlSchemaValidationException, bool> onCaughtXmlSchemaValidationExceptionProcessFunc = null
  455. , Func<XmlSchemaException, bool> onCaughtXmlSchemaExceptionProcessFunc = null
  456. , Func<Exception, bool> onCaughtExceptionProcessFunc = null
  457. )
  458. {
  459. XmlReaderSettings xmlReaderSettings = GetXmlReaderValidationSettings(targetNamespace, xsd);
  460. var r = XsdValidateXml
  461. (
  462. xml
  463. , out errors
  464. , xmlReaderSettings
  465. , caughtExceptionOnlyOnce
  466. , validationEventHandlerAction
  467. , onCaughtXmlSchemaValidationExceptionProcessFunc
  468. , onCaughtXmlSchemaExceptionProcessFunc
  469. , onCaughtExceptionProcessFunc
  470. );
  471. return r;
  472. }
  473. public static XmlReaderSettings GetXmlReaderValidationSettings
  474. (
  475. string targetNamespace
  476. , string xsd
  477. , ValidationType validationType = ValidationType.Schema
  478. , XmlSchemaValidationFlags xmlSchemaValidationFlags =
  479. XmlSchemaValidationFlags.AllowXmlAttributes
  480. | XmlSchemaValidationFlags.AllowXmlAttributes
  481. | XmlSchemaValidationFlags.ProcessIdentityConstraints
  482. | XmlSchemaValidationFlags.ProcessInlineSchema
  483. | XmlSchemaValidationFlags.ProcessSchemaLocation
  484. | XmlSchemaValidationFlags.ReportValidationWarnings
  485. , ValidationEventHandler validationEventHandlerAction = null
  486. )
  487. {
  488. XmlSchemaSet xmlSchemaSet = GetXmlSchemaSet(targetNamespace, xsd);
  489. XmlReaderSettings xmlReaderValidationSettings = new XmlReaderSettings();
  490. xmlReaderValidationSettings.ValidationType = validationType;
  491. xmlReaderValidationSettings.ValidationFlags = xmlSchemaValidationFlags;
  492. xmlReaderValidationSettings.Schemas.Add(xmlSchemaSet);
  493. if (validationEventHandlerAction != null)
  494. {
  495. xmlReaderValidationSettings.ValidationEventHandler += validationEventHandlerAction;
  496. }
  497. return xmlReaderValidationSettings;
  498. }
  499. public static XmlSchemaSet GetXmlSchemaSet(string targetNamespace, string xsd)
  500. {
  501. using (var stringReader = new StringReader(xsd))
  502. {
  503. using (var xmlReader = XmlReader.Create(stringReader))
  504. {
  505. XmlSchemaSet xmlSchemaSet = new XmlSchemaSet();
  506. xmlSchemaSet.Add(targetNamespace, xmlReader);
  507. return xmlSchemaSet;
  508. }
  509. }
  510. }
  511. }
  512. }

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. bootstrapvalidator+bootstrap-select select无法校验问题解决方法

    $("#form_user_input") .bootstrapValidator( { message : 'This value is not valid', excluded ...

  2. 嵌入式 Linux下永久生效环境变量bashrc

    嵌入式 Linux下永久生效环境变量bashrc 1) .bashrc文件 在linux系统普通用户目录(cd /home/xxx)或root用户目录(cd /root)下,用指令ls -al可以看到 ...

  3. jquery插件扩展的学习

    jquery插件的学习可以点击这里 举个例子 //首先先来一个插件 (function($){ $.fn.extent({ bigfont:function(){ return this.css('f ...

  4. MyBatis日志配置

    关于MyBatis的日志,其实MyBatis已经弄得很好了,你甚至都不用配置,只要导入了jar包,MyBatis就会自动寻找. 具体步骤 1.导入jar包,就是把下载MyBatis时,lib里的包复制 ...

  5. iOS小Tip之查看FPS

    可能大家有的时候会想要查看app在运行时的帧率能否达到60帧,如果达不到的话,你可能会想着去优化动画或者其它任何会影响显示性能的问题. 但是,你首先要观察到你的FPS,对吧? 我告诉大家一个简单的方法 ...

  6. ResultSet can not re-read row data for column 1.

    error:ResultSet can not re-read row data for column 1. 将数据类型改为varchar(max)后,查询数据错误 改正:将jdbc驱动改为jtds驱 ...

  7. Spring Boot 乐观锁加锁失败 - 集成AOP

    Spring Boot with AOP 手头上的项目使用了Spring Boot, 在高并发的情况下,经常出现乐观锁加锁失败的情况(OptimisticLockingFailureException ...

  8. 初次启动app校验的活动图和分析

    初次启动活动图 version 1 version 2 version 3 根据上图的活动图分析,可能存在较严重的问题: 主线程中如果发现是sdcard的url,则可能进行重命名 FirstEnter ...

  9. C语言 独木舟问题

    n个人,已知每个人体重,独木舟承重固定,每只独木舟最多坐两个人,可以坐一个人或者两个人.显然要求总重量不超过独木舟承重,假设每个人体重也不超过独木舟承重,问最少需要几只独木舟? 分析:贪心算法,抽象化 ...

  10. visual studio installer 打包123

    下载安装visual studio installer