2
0

XmlSchemaUtil.cs 17 KB

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