XmlSchemaUtil.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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, "Named item " + qname + " was already contained in the schema object table.");
  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, "Named item " + qname + " was already contained in the schema object table.");
  64. else
  65. table [qname].redefinedObject = obj;
  66. return; // never add to the table.
  67. }
  68. else
  69. obj.error (h, "Named item " + qname + " was already contained in the schema object table.");
  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. XmlTextReader xtr = reader as XmlTextReader;
  111. if (xtr != null)
  112. return xtr.GetInternalParserContext ();
  113. XmlNodeReader xnr = reader as XmlNodeReader;
  114. if (xnr != null)
  115. return xnr.GetInternalParserContext ();
  116. XmlValidatingReader xvr = reader as XmlValidatingReader;
  117. if (xvr != null)
  118. return xvr.GetInternalParserContext ();
  119. IHasXmlParserContext xctx = reader as IHasXmlParserContext;
  120. if (xctx != null)
  121. return xctx.ParserContext;
  122. throw new NotSupportedException ("XmlParserContext cannot be acquired from this XmlReader.");
  123. }
  124. public static bool IsBuiltInDatatypeName (XmlQualifiedName qname)
  125. {
  126. if (qname.Namespace != XmlSchema.Namespace)
  127. return false;
  128. switch (qname.Name) {
  129. case "anySimpleType":
  130. case "duration": case "dateTime": case "time":
  131. case "date": case "gYearMonth": case "gYear":
  132. case "gMonthDay": case "gDay": case "gMonth":
  133. case "boolean":
  134. case "base64Binary": case "hexBinary":
  135. case "float": case "double":
  136. case "anyURI":
  137. case "QName":
  138. case "NOTATION":
  139. case "string": case "normalizedString": case "token":
  140. case "language": case "Name": case "NCName":
  141. case "ID": case "IDREF": case "IDREFS":
  142. case "ENTITY": case "ENTITIES":
  143. case "NMTOKEN": case "NMTOKENS":
  144. case "decimal": case "integer":
  145. case "nonPositiveInteger": case "negativeInteger":
  146. case "nonNegativeInteger":
  147. case "unsignedLong": case "unsignedInt":
  148. case "unsignedShort": case "unsignedByte":
  149. case "positiveInteger":
  150. case "long": case "int": case "short": case "byte":
  151. return true;
  152. }
  153. return false;
  154. }
  155. public static bool IsSchemaDatatypeEquals (XsdAnySimpleType st1, object v1,
  156. XsdAnySimpleType st2, object v2)
  157. {
  158. if (v1 == null || v2 == null)
  159. return false;
  160. if (st1 == null)
  161. st1 = XmlSchemaSimpleType.AnySimpleType;
  162. if (st2 == null)
  163. st2 = XmlSchemaSimpleType.AnySimpleType;
  164. Type t = st2.GetType ();
  165. if (st1 is XsdFloat) {
  166. return st2 is XsdFloat && Convert.ToSingle (v1) == Convert.ToSingle (v2);
  167. } else if (st1 is XsdDouble) {
  168. return st2 is XsdDouble && Convert.ToDouble (v1) == Convert.ToDouble (v2);
  169. } else if (st1 is XsdDecimal) {
  170. if (!(st2 is XsdDecimal) || Convert.ToDecimal (v1) != Convert.ToDecimal (v2))
  171. return false;
  172. if (st1 is XsdNonPositiveInteger)
  173. return st2 is XsdNonPositiveInteger || t == typeof (XsdDecimal) || t == typeof (XsdInteger);
  174. else if (st1 is XsdPositiveInteger)
  175. return st2 is XsdPositiveInteger || t == typeof (XsdDecimal) ||
  176. t == typeof (XsdInteger) || t == typeof (XsdNonNegativeInteger);
  177. else if (st1 is XsdUnsignedLong)
  178. return st2 is XsdUnsignedLong || t == typeof (XsdDecimal) ||
  179. t == typeof (XsdInteger) || t == typeof (XsdNonNegativeInteger);
  180. else if (st1 is XsdNonNegativeInteger)
  181. return st2 is XsdNonNegativeInteger || t == typeof (XsdDecimal) || t == typeof (XsdInteger);
  182. else if (st1 is XsdLong)
  183. return st2 is XsdLong || t == typeof (XsdDecimal) || t == typeof (XsdInteger);
  184. return true;
  185. }
  186. else if (!v1.Equals (v2))
  187. return false;
  188. if (st1 is XsdString) {
  189. if (!(st2 is XsdString))
  190. return false;
  191. if (st1 is XsdNMToken && (st2 is XsdLanguage || st2 is XsdName))
  192. return false;
  193. if (st2 is XsdNMToken && (st1 is XsdLanguage || st1 is XsdName))
  194. return false;
  195. if (st1 is XsdName && (st2 is XsdLanguage || st2 is XsdNMToken))
  196. return false;
  197. if (st2 is XsdName && (st1 is XsdLanguage || st1 is XsdNMToken))
  198. return false;
  199. if (st1 is XsdID && st2 is XsdIDRef)
  200. return false;
  201. if (st1 is XsdIDRef && st2 is XsdID)
  202. return false;
  203. }
  204. else if (st1 != st2)
  205. return false;
  206. return true;
  207. }
  208. public static bool IsValidQName(string qname)
  209. {
  210. foreach(string part in qname.Split(new char[]{':'},2))
  211. {
  212. if(!CheckNCName(part))
  213. return false;
  214. }
  215. return true;
  216. }
  217. //FIXME: First remove all the multiple instances of whitespace and then return the strings.
  218. //The current method returns empty strings if there are two or more consecutive whitespaces.
  219. public static string[] SplitList(string list)
  220. {
  221. if(list == null || list == string.Empty)
  222. return new string [0];
  223. ArrayList al = null;
  224. int start = 0;
  225. bool wait = true;
  226. for (int i = 0; i < list.Length; i++) {
  227. switch (list [i]) {
  228. case ' ':
  229. case '\r':
  230. case '\n':
  231. case '\t':
  232. if (!wait) {
  233. if (al == null)
  234. al = new ArrayList ();
  235. al.Add (list.Substring (start, i - start));
  236. }
  237. wait = true;
  238. break;
  239. default:
  240. if (wait) {
  241. wait = false;
  242. start = i;
  243. }
  244. break;
  245. }
  246. }
  247. if (!wait && start == 0)
  248. return new string [] {list};
  249. if (!wait && start < list.Length)
  250. al.Add (start == 0 ? list : list.Substring (start));
  251. return al.ToArray (typeof (string)) as string [];
  252. }
  253. public static void ReadUnhandledAttribute(XmlReader reader, XmlSchemaObject xso)
  254. {
  255. if(reader.Prefix == "xmlns")
  256. xso.Namespaces.Add(reader.LocalName, reader.Value);
  257. else if(reader.Name == "xmlns")
  258. xso.Namespaces.Add("",reader.Value);
  259. else
  260. {
  261. if(xso.unhandledAttributeList == null)
  262. xso.unhandledAttributeList = new System.Collections.ArrayList();
  263. XmlAttribute attr = new XmlDocument().CreateAttribute(reader.LocalName,reader.NamespaceURI);
  264. attr.Value = reader.Value;
  265. ParseWsdlArrayType (reader, attr);
  266. xso.unhandledAttributeList.Add(attr);
  267. }
  268. }
  269. static void ParseWsdlArrayType (XmlReader reader, XmlAttribute attr)
  270. {
  271. if (attr.NamespaceURI == XmlSerializer.WsdlNamespace && attr.LocalName == "arrayType")
  272. {
  273. string ns = "", type, dimensions;
  274. TypeTranslator.ParseArrayType (attr.Value, out type, out ns, out dimensions);
  275. if (ns != "") ns = reader.LookupNamespace (ns) + ":";
  276. attr.Value = ns + type + dimensions;
  277. }
  278. }
  279. public static bool ReadBoolAttribute(XmlReader reader, out Exception innerExcpetion)
  280. {
  281. innerExcpetion = null;
  282. try
  283. {
  284. bool val = XmlConvert.ToBoolean(reader.Value);
  285. return val;
  286. }
  287. catch(Exception ex)
  288. {
  289. innerExcpetion = ex;
  290. return false;
  291. }
  292. }
  293. public static decimal ReadDecimalAttribute(XmlReader reader, out Exception innerExcpetion)
  294. {
  295. innerExcpetion = null;
  296. try
  297. {
  298. decimal val = XmlConvert.ToDecimal(reader.Value);
  299. return val;
  300. }
  301. catch(Exception ex)
  302. {
  303. innerExcpetion = ex;
  304. return decimal.Zero;
  305. }
  306. }
  307. // Is some value is read, return it.
  308. // If no values return empty.
  309. // If exception, return none
  310. public static XmlSchemaDerivationMethod ReadDerivationAttribute(XmlReader reader, out Exception innerExcpetion, string name, XmlSchemaDerivationMethod allowed)
  311. {
  312. innerExcpetion = null;
  313. try
  314. {
  315. string list = reader.Value;
  316. string warn = "";
  317. XmlSchemaDerivationMethod val = 0;
  318. if(list.IndexOf("#all") != -1 && list.Trim() != "#all")
  319. {
  320. innerExcpetion = new Exception(list+" is not a valid value for "+ name +". #all if present must be the only value");
  321. return XmlSchemaDerivationMethod.All;
  322. }
  323. foreach(string xsdm in XmlSchemaUtil.SplitList(list))
  324. {
  325. switch(xsdm)
  326. {
  327. case "":
  328. val = AddFlag (val, XmlSchemaDerivationMethod.Empty, allowed); break;
  329. case "#all":
  330. val = AddFlag (val,XmlSchemaDerivationMethod.All, allowed); break;
  331. case "substitution":
  332. val = AddFlag (val,XmlSchemaDerivationMethod.Substitution, allowed); break;
  333. case "extension":
  334. val = AddFlag (val,XmlSchemaDerivationMethod.Extension, allowed); break;
  335. case "restriction":
  336. val = AddFlag (val,XmlSchemaDerivationMethod.Restriction, allowed); break;
  337. case "list":
  338. val = AddFlag (val,XmlSchemaDerivationMethod.List, allowed); break;
  339. case "union":
  340. val = AddFlag (val,XmlSchemaDerivationMethod.Union, allowed); break;
  341. default:
  342. warn += xsdm + " "; break;
  343. }
  344. }
  345. if(warn != "")
  346. innerExcpetion = new Exception(warn + "is/are not valid values for " + name);
  347. return val;
  348. }
  349. catch(Exception ex)
  350. {
  351. innerExcpetion = ex;
  352. return XmlSchemaDerivationMethod.None;
  353. }
  354. }
  355. private static XmlSchemaDerivationMethod AddFlag (XmlSchemaDerivationMethod dst,
  356. XmlSchemaDerivationMethod add, XmlSchemaDerivationMethod allowed)
  357. {
  358. if ((add & allowed) == 0 && allowed != XmlSchemaDerivationMethod.All)
  359. throw new ArgumentException (add + " is not allowed in this attribute.");
  360. if ((dst & add) != 0)
  361. throw new ArgumentException (add + " is already specified in this attribute.");
  362. return dst | add;
  363. }
  364. public static XmlSchemaForm ReadFormAttribute(XmlReader reader, out Exception innerExcpetion)
  365. {
  366. innerExcpetion = null;
  367. XmlSchemaForm val = XmlSchemaForm.None;
  368. switch(reader.Value)
  369. {
  370. case "qualified":
  371. val = XmlSchemaForm.Qualified; break;
  372. case "unqualified":
  373. val = XmlSchemaForm.Unqualified; break;
  374. default:
  375. innerExcpetion = new Exception("only qualified or unqulified is a valid value"); break;
  376. }
  377. return val;
  378. }
  379. public static XmlSchemaContentProcessing ReadProcessingAttribute(XmlReader reader, out Exception innerExcpetion)
  380. {
  381. innerExcpetion = null;
  382. XmlSchemaContentProcessing val = XmlSchemaContentProcessing.None;
  383. switch(reader.Value)
  384. {
  385. case "lax":
  386. val = XmlSchemaContentProcessing.Lax; break;
  387. case "strict":
  388. val = XmlSchemaContentProcessing.Strict; break;
  389. case "skip":
  390. val = XmlSchemaContentProcessing.Skip; break;
  391. default:
  392. innerExcpetion = new Exception("only lax , strict or skip are valid values for processContents");
  393. break;
  394. }
  395. return val;
  396. }
  397. public static XmlSchemaUse ReadUseAttribute(XmlReader reader, out Exception innerExcpetion)
  398. {
  399. innerExcpetion = null;
  400. XmlSchemaUse val = XmlSchemaUse.None;
  401. switch(reader.Value)
  402. {
  403. case "optional":
  404. val = XmlSchemaUse.Optional; break;
  405. case "prohibited":
  406. val = XmlSchemaUse.Prohibited; break;
  407. case "required":
  408. val = XmlSchemaUse.Required; break;
  409. default:
  410. innerExcpetion = new Exception("only optional , prohibited or required are valid values for use");
  411. break;
  412. }
  413. return val;
  414. }
  415. public static XmlQualifiedName ReadQNameAttribute(XmlReader reader, out Exception innerEx)
  416. {
  417. return ToQName(reader, reader.Value, out innerEx);
  418. }
  419. //While Creating a XmlQualifedName, we should check:
  420. // 1. If a prefix is present, its namespace should be resolvable.
  421. // 2. If a prefix is not present, and if the defaultNamespace is set,
  422. public static XmlQualifiedName ToQName(XmlReader reader, string qnamestr, out Exception innerEx)
  423. {
  424. string ns;
  425. string name;
  426. XmlQualifiedName qname;
  427. innerEx = null;
  428. if(!IsValidQName(qnamestr))
  429. {
  430. innerEx = new Exception(qnamestr + " is an invalid QName. Either name or namespace is not a NCName");
  431. return XmlQualifiedName.Empty;
  432. }
  433. string[] values = qnamestr.Split(new char[]{':'},2);
  434. if(values.Length == 2)
  435. {
  436. ns = reader.LookupNamespace(values[0]);
  437. if(ns == null)
  438. {
  439. innerEx = new Exception("Namespace Prefix '"+values[0]+"could not be resolved");
  440. return XmlQualifiedName.Empty;
  441. }
  442. name = values[1];
  443. }
  444. else
  445. {
  446. //Default Namespace
  447. ns = reader.LookupNamespace("");
  448. name = values[0];
  449. }
  450. qname = new XmlQualifiedName(name,ns);
  451. return qname;
  452. }
  453. public static int ValidateAttributesResolved (
  454. XmlSchemaObjectTable attributesResolved,
  455. ValidationEventHandler h,
  456. XmlSchema schema,
  457. XmlSchemaObjectCollection attributes,
  458. XmlSchemaAnyAttribute anyAttribute,
  459. ref XmlSchemaAnyAttribute anyAttributeUse,
  460. XmlSchemaAttributeGroup redefined)
  461. {
  462. int errorCount = 0;
  463. if (anyAttribute != null && anyAttributeUse == null)
  464. anyAttributeUse = anyAttribute;
  465. foreach (XmlSchemaObject xsobj in attributes) {
  466. XmlSchemaAttributeGroupRef grpRef = xsobj as XmlSchemaAttributeGroupRef;
  467. if (grpRef != null) {
  468. // Resolve attributeGroup redefinition.
  469. XmlSchemaAttributeGroup grp = null;
  470. if (redefined != null && grpRef.RefName == redefined.QualifiedName)
  471. grp = redefined;
  472. else
  473. grp = schema.AttributeGroups [grpRef.RefName] as XmlSchemaAttributeGroup;
  474. // otherwise, it might be missing sub components.
  475. if (grp == null) {
  476. if (!schema.missedSubComponents)// && schema.Schemas [grpRef.RefName.Namespace] != null)
  477. grpRef.error (h, "Referenced attribute group " + grpRef.RefName + " was not found in the corresponding schema.");
  478. continue;
  479. }
  480. if (grp.AttributeGroupRecursionCheck) {
  481. grp.error (h, "Attribute group recursion was found: " + grpRef.RefName);
  482. continue;
  483. }
  484. try {
  485. grp.AttributeGroupRecursionCheck = true;
  486. errorCount += grp.Validate (h, schema);
  487. } finally {
  488. grp.AttributeGroupRecursionCheck = false;
  489. }
  490. if (grp.AnyAttributeUse != null) {
  491. if (anyAttribute == null)
  492. anyAttributeUse = grp.AnyAttributeUse;
  493. }
  494. foreach (DictionaryEntry entry in grp.AttributeUses) {
  495. XmlSchemaAttribute attr = (XmlSchemaAttribute) entry.Value;
  496. #if BUGGY_MS_COMPLIANT
  497. if (attr.Use == XmlSchemaUse.Prohibited)
  498. continue;
  499. #endif
  500. if (attr.RefName != null && attr.RefName != XmlQualifiedName.Empty)
  501. AddToTable (attributesResolved, attr, attr.RefName, h);
  502. else
  503. AddToTable (attributesResolved, attr, attr.QualifiedName, h);
  504. }
  505. } else {
  506. XmlSchemaAttribute attr = xsobj as XmlSchemaAttribute;
  507. if (attr != null) {
  508. errorCount += attr.Validate (h, schema);
  509. #if BUGGY_MS_COMPLIANT
  510. if (attr.Use == XmlSchemaUse.Prohibited)
  511. continue;
  512. #endif
  513. if (attr.RefName != null && attr.RefName != XmlQualifiedName.Empty)
  514. AddToTable (attributesResolved, attr, attr.RefName, h);
  515. else
  516. AddToTable (attributesResolved, attr, attr.QualifiedName, h);
  517. } else {
  518. if (anyAttribute == null) {
  519. anyAttributeUse = (XmlSchemaAnyAttribute) xsobj;
  520. anyAttribute.Validate (h, schema);
  521. }
  522. }
  523. }
  524. }
  525. return errorCount;
  526. }
  527. }
  528. }