XmlSchemaUtil.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. //
  2. // Permission is hereby granted, free of charge, to any person obtaining
  3. // a copy of this software and associated documentation files (the
  4. // "Software"), to deal in the Software without restriction, including
  5. // without limitation the rights to use, copy, modify, merge, publish,
  6. // distribute, sublicense, and/or sell copies of the Software, and to
  7. // permit persons to whom the Software is furnished to do so, subject to
  8. // the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be
  11. // included in all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  17. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  18. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  19. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  20. //
  21. using System;
  22. using System.Xml;
  23. using System.Collections;
  24. using Mono.Xml;
  25. using Mono.Xml.Schema;
  26. using System.Xml.Serialization;
  27. namespace System.Xml.Schema
  28. {
  29. /// <summary>
  30. /// All Methods in this class should use XmlConvert. Some Methods are not present in the
  31. /// MS Implementation. We should provide them.
  32. /// </summary>
  33. internal class XmlSchemaUtil
  34. {
  35. static XmlSchemaUtil ()
  36. {
  37. FinalAllowed = XmlSchemaDerivationMethod.Restriction |
  38. XmlSchemaDerivationMethod.Extension;
  39. ComplexTypeBlockAllowed = FinalAllowed;
  40. ElementBlockAllowed = XmlSchemaDerivationMethod.Substitution |
  41. FinalAllowed;
  42. }
  43. internal static XmlSchemaDerivationMethod FinalAllowed;
  44. internal static XmlSchemaDerivationMethod ElementBlockAllowed;
  45. internal static XmlSchemaDerivationMethod ComplexTypeBlockAllowed;
  46. public static void AddToTable (XmlSchemaObjectTable table, XmlSchemaObject obj,
  47. XmlQualifiedName qname, ValidationEventHandler h)
  48. {
  49. if (table.Contains (qname)) {
  50. // FIXME: This logic unexpectedly allows
  51. // one redefining item and two or more redefining items.
  52. // FIXME: redefining item is not simple replacement,
  53. // but much more complex stuff.
  54. if (obj.isRedefineChild) { // take precedence.
  55. if (obj.redefinedObject != null)
  56. obj.error (h, String.Format ("Named item {0} was already contained in the schema object table.", qname));
  57. else
  58. obj.redefinedObject = table [qname];
  59. table.Set (qname, obj);
  60. }
  61. else if (table [qname].isRedefineChild) {
  62. if (table [qname].redefinedObject != null)
  63. obj.error (h, String.Format ("Named item {0} was already contained in the schema object table.", qname));
  64. else
  65. table [qname].redefinedObject = obj;
  66. return; // never add to the table.
  67. }
  68. else
  69. obj.error (h, String.Format ("Named item {0} was already contained in the schema object table.", qname));
  70. }
  71. else
  72. table.Set (qname, obj);
  73. }
  74. public static void CompileID(string id, XmlSchemaObject xso, Hashtable idCollection, ValidationEventHandler h)
  75. {
  76. //check if the string conforms to http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/datatypes.html#ID
  77. // 1. ID must be a NCName
  78. // 2. ID must be unique in the schema
  79. if(id == null)
  80. return;
  81. if(!CheckNCName(id))
  82. xso.error(h,id+" is not a valid id attribute");
  83. else if(idCollection.ContainsKey(id))
  84. xso.error(h,"Duplicate id attribute "+id);
  85. else
  86. idCollection.Add(id,xso);
  87. }
  88. public static bool CheckAnyUri(string uri)
  89. {
  90. if (uri.StartsWith ("##"))
  91. return false;
  92. return true;
  93. }
  94. public static bool CheckNormalizedString(string token)
  95. {
  96. return true;
  97. }
  98. public static bool CheckNCName(string name)
  99. {
  100. //check if the string conforms to http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/datatypes.html#NCName
  101. return XmlChar.IsNCName (name);
  102. }
  103. public static bool CheckQName(XmlQualifiedName qname)
  104. {
  105. // What is this doing?
  106. return true;
  107. }
  108. public static XmlParserContext GetParserContext (XmlReader reader)
  109. {
  110. IHasXmlParserContext xctx = reader as IHasXmlParserContext;
  111. if (xctx != null)
  112. return xctx.ParserContext;
  113. throw new NotSupportedException ("XmlParserContext cannot be acquired from this XmlReader.");
  114. }
  115. public static bool IsBuiltInDatatypeName (XmlQualifiedName qname)
  116. {
  117. if (qname.Namespace == XmlSchema.XdtNamespace) {
  118. switch (qname.Name) {
  119. case "anyAtomicType":
  120. case "untypedAtomic":
  121. case "dayTimeDuration":
  122. case "yearMonthDuration":
  123. return true;
  124. default:
  125. return false;
  126. }
  127. }
  128. if (qname.Namespace != XmlSchema.Namespace)
  129. return false;
  130. switch (qname.Name) {
  131. case "anySimpleType":
  132. case "duration": case "dateTime": case "time":
  133. case "date": case "gYearMonth": case "gYear":
  134. case "gMonthDay": case "gDay": case "gMonth":
  135. case "boolean":
  136. case "base64Binary": case "hexBinary":
  137. case "float": case "double":
  138. case "anyURI":
  139. case "QName":
  140. case "NOTATION":
  141. case "string": case "normalizedString": case "token":
  142. case "language": case "Name": case "NCName":
  143. case "ID": case "IDREF": case "IDREFS":
  144. case "ENTITY": case "ENTITIES":
  145. case "NMTOKEN": case "NMTOKENS":
  146. case "decimal": case "integer":
  147. case "nonPositiveInteger": case "negativeInteger":
  148. case "nonNegativeInteger":
  149. case "unsignedLong": case "unsignedInt":
  150. case "unsignedShort": case "unsignedByte":
  151. case "positiveInteger":
  152. case "long": case "int": case "short": case "byte":
  153. return true;
  154. }
  155. return false;
  156. }
  157. public static bool IsSchemaDatatypeEquals (XsdAnySimpleType st1, object v1,
  158. XsdAnySimpleType st2, object v2)
  159. {
  160. if (v1 == null || v2 == null)
  161. return false;
  162. if (st1 == null)
  163. st1 = XmlSchemaSimpleType.AnySimpleType;
  164. if (st2 == null)
  165. st2 = XmlSchemaSimpleType.AnySimpleType;
  166. Type t = st2.GetType ();
  167. if (st1 is XsdFloat) {
  168. return st2 is XsdFloat && Convert.ToSingle (v1) == Convert.ToSingle (v2);
  169. } else if (st1 is XsdDouble) {
  170. return st2 is XsdDouble && Convert.ToDouble (v1) == Convert.ToDouble (v2);
  171. } else if (st1 is XsdDecimal) {
  172. if (!(st2 is XsdDecimal) || Convert.ToDecimal (v1) != Convert.ToDecimal (v2))
  173. return false;
  174. if (st1 is XsdNonPositiveInteger)
  175. return st2 is XsdNonPositiveInteger || t == typeof (XsdDecimal) || t == typeof (XsdInteger);
  176. else if (st1 is XsdPositiveInteger)
  177. return st2 is XsdPositiveInteger || t == typeof (XsdDecimal) ||
  178. t == typeof (XsdInteger) || t == typeof (XsdNonNegativeInteger);
  179. else if (st1 is XsdUnsignedLong)
  180. return st2 is XsdUnsignedLong || t == typeof (XsdDecimal) ||
  181. t == typeof (XsdInteger) || t == typeof (XsdNonNegativeInteger);
  182. else if (st1 is XsdNonNegativeInteger)
  183. return st2 is XsdNonNegativeInteger || t == typeof (XsdDecimal) || t == typeof (XsdInteger);
  184. else if (st1 is XsdLong)
  185. return st2 is XsdLong || t == typeof (XsdDecimal) || t == typeof (XsdInteger);
  186. return true;
  187. }
  188. else if (!v1.Equals (v2))
  189. return false;
  190. if (st1 is XsdString) {
  191. if (!(st2 is XsdString))
  192. return false;
  193. if (st1 is XsdNMToken && (st2 is XsdLanguage || st2 is XsdName))
  194. return false;
  195. if (st2 is XsdNMToken && (st1 is XsdLanguage || st1 is XsdName))
  196. return false;
  197. if (st1 is XsdName && (st2 is XsdLanguage || st2 is XsdNMToken))
  198. return false;
  199. if (st2 is XsdName && (st1 is XsdLanguage || st1 is XsdNMToken))
  200. return false;
  201. if (st1 is XsdID && st2 is XsdIDRef)
  202. return false;
  203. if (st1 is XsdIDRef && st2 is XsdID)
  204. return false;
  205. }
  206. else if (st1 != st2)
  207. return false;
  208. return true;
  209. }
  210. public static bool IsValidQName(string qname)
  211. {
  212. foreach(string part in qname.Split(new char[]{':'},2))
  213. {
  214. if(!CheckNCName(part))
  215. return false;
  216. }
  217. return true;
  218. }
  219. //FIXME: First remove all the multiple instances of whitespace and then return the strings.
  220. //The current method returns empty strings if there are two or more consecutive whitespaces.
  221. public static string[] SplitList(string list)
  222. {
  223. if(list == null || list == string.Empty)
  224. return new string [0];
  225. ArrayList al = null;
  226. int start = 0;
  227. bool wait = true;
  228. for (int i = 0; i < list.Length; i++) {
  229. switch (list [i]) {
  230. case ' ':
  231. case '\r':
  232. case '\n':
  233. case '\t':
  234. if (!wait) {
  235. if (al == null)
  236. al = new ArrayList ();
  237. al.Add (list.Substring (start, i - start));
  238. }
  239. wait = true;
  240. break;
  241. default:
  242. if (wait) {
  243. wait = false;
  244. start = i;
  245. }
  246. break;
  247. }
  248. }
  249. if (!wait && start == 0)
  250. return new string [] {list};
  251. if (!wait && start < list.Length)
  252. al.Add (start == 0 ? list : list.Substring (start));
  253. return al.ToArray (typeof (string)) as string [];
  254. }
  255. public static void ReadUnhandledAttribute(XmlReader reader, XmlSchemaObject xso)
  256. {
  257. if(reader.Prefix == "xmlns")
  258. xso.Namespaces.Add(reader.LocalName, reader.Value);
  259. else if(reader.Name == "xmlns")
  260. xso.Namespaces.Add("",reader.Value);
  261. else
  262. {
  263. if(xso.unhandledAttributeList == null)
  264. xso.unhandledAttributeList = new System.Collections.ArrayList();
  265. XmlAttribute attr = new XmlDocument().CreateAttribute(reader.LocalName,reader.NamespaceURI);
  266. attr.Value = reader.Value;
  267. ParseWsdlArrayType (reader, attr);
  268. xso.unhandledAttributeList.Add(attr);
  269. }
  270. }
  271. static void ParseWsdlArrayType (XmlReader reader, XmlAttribute attr)
  272. {
  273. if (attr.NamespaceURI == XmlSerializer.WsdlNamespace && attr.LocalName == "arrayType")
  274. {
  275. string ns = "", type, dimensions;
  276. TypeTranslator.ParseArrayType (attr.Value, out type, out ns, out dimensions);
  277. if (ns != "") ns = reader.LookupNamespace (ns) + ":";
  278. attr.Value = ns + type + dimensions;
  279. }
  280. }
  281. public static bool ReadBoolAttribute(XmlReader reader, out Exception innerExcpetion)
  282. {
  283. innerExcpetion = null;
  284. try
  285. {
  286. bool val = XmlConvert.ToBoolean(reader.Value);
  287. return val;
  288. }
  289. catch(Exception ex)
  290. {
  291. innerExcpetion = ex;
  292. return false;
  293. }
  294. }
  295. public static decimal ReadDecimalAttribute(XmlReader reader, out Exception innerExcpetion)
  296. {
  297. innerExcpetion = null;
  298. try
  299. {
  300. decimal val = XmlConvert.ToDecimal(reader.Value);
  301. return val;
  302. }
  303. catch(Exception ex)
  304. {
  305. innerExcpetion = ex;
  306. return decimal.Zero;
  307. }
  308. }
  309. // Is some value is read, return it.
  310. // If no values return empty.
  311. // If exception, return none
  312. public static XmlSchemaDerivationMethod ReadDerivationAttribute(XmlReader reader, out Exception innerExcpetion, string name, XmlSchemaDerivationMethod allowed)
  313. {
  314. innerExcpetion = null;
  315. try
  316. {
  317. string list = reader.Value;
  318. string warn = "";
  319. XmlSchemaDerivationMethod val = 0;
  320. if(list.IndexOf("#all") != -1 && list.Trim() != "#all")
  321. {
  322. innerExcpetion = new Exception(list+" is not a valid value for "+ name +". #all if present must be the only value");
  323. return XmlSchemaDerivationMethod.All;
  324. }
  325. foreach(string xsdm in XmlSchemaUtil.SplitList(list))
  326. {
  327. switch(xsdm)
  328. {
  329. case "":
  330. val = AddFlag (val, XmlSchemaDerivationMethod.Empty, allowed); break;
  331. case "#all":
  332. val = AddFlag (val,XmlSchemaDerivationMethod.All, allowed); break;
  333. case "substitution":
  334. val = AddFlag (val,XmlSchemaDerivationMethod.Substitution, allowed); break;
  335. case "extension":
  336. val = AddFlag (val,XmlSchemaDerivationMethod.Extension, allowed); break;
  337. case "restriction":
  338. val = AddFlag (val,XmlSchemaDerivationMethod.Restriction, allowed); break;
  339. case "list":
  340. val = AddFlag (val,XmlSchemaDerivationMethod.List, allowed); break;
  341. case "union":
  342. val = AddFlag (val,XmlSchemaDerivationMethod.Union, allowed); break;
  343. default:
  344. warn += xsdm + " "; break;
  345. }
  346. }
  347. if(warn != "")
  348. innerExcpetion = new Exception(warn + "is/are not valid values for " + name);
  349. return val;
  350. }
  351. catch(Exception ex)
  352. {
  353. innerExcpetion = ex;
  354. return XmlSchemaDerivationMethod.None;
  355. }
  356. }
  357. private static XmlSchemaDerivationMethod AddFlag (XmlSchemaDerivationMethod dst,
  358. XmlSchemaDerivationMethod add, XmlSchemaDerivationMethod allowed)
  359. {
  360. if ((add & allowed) == 0 && allowed != XmlSchemaDerivationMethod.All)
  361. throw new ArgumentException (add + " is not allowed in this attribute.");
  362. if ((dst & add) != 0)
  363. throw new ArgumentException (add + " is already specified in this attribute.");
  364. return dst | add;
  365. }
  366. public static XmlSchemaForm ReadFormAttribute(XmlReader reader, out Exception innerExcpetion)
  367. {
  368. innerExcpetion = null;
  369. XmlSchemaForm val = XmlSchemaForm.None;
  370. switch(reader.Value)
  371. {
  372. case "qualified":
  373. val = XmlSchemaForm.Qualified; break;
  374. case "unqualified":
  375. val = XmlSchemaForm.Unqualified; break;
  376. default:
  377. innerExcpetion = new Exception("only qualified or unqulified is a valid value"); break;
  378. }
  379. return val;
  380. }
  381. public static XmlSchemaContentProcessing ReadProcessingAttribute(XmlReader reader, out Exception innerExcpetion)
  382. {
  383. innerExcpetion = null;
  384. XmlSchemaContentProcessing val = XmlSchemaContentProcessing.None;
  385. switch(reader.Value)
  386. {
  387. case "lax":
  388. val = XmlSchemaContentProcessing.Lax; break;
  389. case "strict":
  390. val = XmlSchemaContentProcessing.Strict; break;
  391. case "skip":
  392. val = XmlSchemaContentProcessing.Skip; break;
  393. default:
  394. innerExcpetion = new Exception("only lax , strict or skip are valid values for processContents");
  395. break;
  396. }
  397. return val;
  398. }
  399. public static XmlSchemaUse ReadUseAttribute(XmlReader reader, out Exception innerExcpetion)
  400. {
  401. innerExcpetion = null;
  402. XmlSchemaUse val = XmlSchemaUse.None;
  403. switch(reader.Value)
  404. {
  405. case "optional":
  406. val = XmlSchemaUse.Optional; break;
  407. case "prohibited":
  408. val = XmlSchemaUse.Prohibited; break;
  409. case "required":
  410. val = XmlSchemaUse.Required; break;
  411. default:
  412. innerExcpetion = new Exception("only optional , prohibited or required are valid values for use");
  413. break;
  414. }
  415. return val;
  416. }
  417. public static XmlQualifiedName ReadQNameAttribute(XmlReader reader, out Exception innerEx)
  418. {
  419. return ToQName(reader, reader.Value, out innerEx);
  420. }
  421. //While Creating a XmlQualifedName, we should check:
  422. // 1. If a prefix is present, its namespace should be resolvable.
  423. // 2. If a prefix is not present, and if the defaultNamespace is set,
  424. public static XmlQualifiedName ToQName(XmlReader reader, string qnamestr, out Exception innerEx)
  425. {
  426. string ns;
  427. string name;
  428. XmlQualifiedName qname;
  429. innerEx = null;
  430. if(!IsValidQName(qnamestr))
  431. {
  432. innerEx = new Exception(qnamestr + " is an invalid QName. Either name or namespace is not a NCName");
  433. return XmlQualifiedName.Empty;
  434. }
  435. string[] values = qnamestr.Split(new char[]{':'},2);
  436. if(values.Length == 2)
  437. {
  438. ns = reader.LookupNamespace(values[0]);
  439. if(ns == null)
  440. {
  441. innerEx = new Exception("Namespace Prefix '"+values[0]+"could not be resolved");
  442. return XmlQualifiedName.Empty;
  443. }
  444. name = values[1];
  445. }
  446. else
  447. {
  448. //Default Namespace
  449. ns = reader.LookupNamespace("");
  450. name = values[0];
  451. }
  452. qname = new XmlQualifiedName(name,ns);
  453. return qname;
  454. }
  455. public static int ValidateAttributesResolved (
  456. XmlSchemaObjectTable attributesResolved,
  457. ValidationEventHandler h,
  458. XmlSchema schema,
  459. XmlSchemaObjectCollection attributes,
  460. XmlSchemaAnyAttribute anyAttribute,
  461. ref XmlSchemaAnyAttribute anyAttributeUse,
  462. XmlSchemaAttributeGroup redefined)
  463. {
  464. int errorCount = 0;
  465. if (anyAttribute != null && anyAttributeUse == null)
  466. anyAttributeUse = anyAttribute;
  467. foreach (XmlSchemaObject xsobj in attributes) {
  468. XmlSchemaAttributeGroupRef grpRef = xsobj as XmlSchemaAttributeGroupRef;
  469. if (grpRef != null) {
  470. // Resolve attributeGroup redefinition.
  471. XmlSchemaAttributeGroup grp = null;
  472. if (redefined != null && grpRef.RefName == redefined.QualifiedName)
  473. grp = redefined;
  474. else
  475. grp = schema.AttributeGroups [grpRef.RefName] as XmlSchemaAttributeGroup;
  476. // otherwise, it might be missing sub components.
  477. if (grp == null) {
  478. if (!schema.missedSubComponents)// && schema.Schemas [grpRef.RefName.Namespace] != null)
  479. grpRef.error (h, "Referenced attribute group " + grpRef.RefName + " was not found in the corresponding schema.");
  480. continue;
  481. }
  482. if (grp.AttributeGroupRecursionCheck) {
  483. grp.error (h, "Attribute group recursion was found: " + grpRef.RefName);
  484. continue;
  485. }
  486. try {
  487. grp.AttributeGroupRecursionCheck = true;
  488. errorCount += grp.Validate (h, schema);
  489. } finally {
  490. grp.AttributeGroupRecursionCheck = false;
  491. }
  492. if (grp.AnyAttributeUse != null) {
  493. if (anyAttribute == null)
  494. anyAttributeUse = grp.AnyAttributeUse;
  495. }
  496. foreach (DictionaryEntry entry in grp.AttributeUses) {
  497. XmlSchemaAttribute attr = (XmlSchemaAttribute) entry.Value;
  498. #if BUGGY_MS_COMPLIANT
  499. if (attr.Use == XmlSchemaUse.Prohibited)
  500. continue;
  501. #endif
  502. if (attr.RefName != null && attr.RefName != XmlQualifiedName.Empty)
  503. AddToTable (attributesResolved, attr, attr.RefName, h);
  504. else
  505. AddToTable (attributesResolved, attr, attr.QualifiedName, h);
  506. }
  507. } else {
  508. XmlSchemaAttribute attr = xsobj as XmlSchemaAttribute;
  509. if (attr != null) {
  510. errorCount += attr.Validate (h, schema);
  511. #if BUGGY_MS_COMPLIANT
  512. if (attr.Use == XmlSchemaUse.Prohibited)
  513. continue;
  514. #endif
  515. if (attr.RefName != null && attr.RefName != XmlQualifiedName.Empty)
  516. AddToTable (attributesResolved, attr, attr.RefName, h);
  517. else
  518. AddToTable (attributesResolved, attr, attr.QualifiedName, h);
  519. } else {
  520. if (anyAttribute == null) {
  521. anyAttributeUse = (XmlSchemaAnyAttribute) xsobj;
  522. anyAttribute.Validate (h, schema);
  523. }
  524. }
  525. }
  526. }
  527. return errorCount;
  528. }
  529. }
  530. }