XmlSchemaUtil.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 CheckLanguage(string lang)
  79. // {
  80. //check if the string conforms to http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/datatypes.html#language
  81. // return true;
  82. // }
  83. public static bool CheckNCName(string name)
  84. {
  85. //check if the string conforms to http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/datatypes.html#NCName
  86. return XmlChar.IsNCName (name);
  87. }
  88. public static bool CheckQName(XmlQualifiedName qname)
  89. {
  90. // What is this doing?
  91. return true;
  92. }
  93. public static XmlParserContext GetParserContext (XmlReader reader)
  94. {
  95. XmlTextReader xtr = reader as XmlTextReader;
  96. if (xtr != null)
  97. return xtr.GetInternalParserContext ();
  98. XmlNodeReader xnr = reader as XmlNodeReader;
  99. if (xnr != null)
  100. return xnr.GetInternalParserContext ();
  101. XmlValidatingReader xvr = reader as XmlValidatingReader;
  102. if (xvr != null)
  103. return xvr.GetInternalParserContext ();
  104. IHasXmlParserContext xctx = reader as IHasXmlParserContext;
  105. if (xctx != null)
  106. return xctx.ParserContext;
  107. throw new NotSupportedException ("XmlParserContext cannot be acquired from this XmlReader.");
  108. }
  109. public static bool IsSchemaDatatypeEquals (XsdAnySimpleType st1, object v1,
  110. XsdAnySimpleType st2, object v2)
  111. {
  112. if (v1 == null || v2 == null)
  113. return false;
  114. if (st1 == null)
  115. st1 = XmlSchemaSimpleType.AnySimpleType;
  116. if (st2 == null)
  117. st2 = XmlSchemaSimpleType.AnySimpleType;
  118. Type t = st2.GetType ();
  119. if (st1 is XsdFloat) {
  120. return st2 is XsdFloat && Convert.ToSingle (v1) == Convert.ToSingle (v2);
  121. } else if (st1 is XsdDouble) {
  122. return st2 is XsdDouble && Convert.ToDouble (v1) == Convert.ToDouble (v2);
  123. } else if (st1 is XsdDecimal) {
  124. if (!(st2 is XsdDecimal) || Convert.ToDecimal (v1) != Convert.ToDecimal (v2))
  125. return false;
  126. if (st1 is XsdNonPositiveInteger)
  127. return st2 is XsdNonPositiveInteger || t == typeof (XsdDecimal) || t == typeof (XsdInteger);
  128. else if (st1 is XsdPositiveInteger)
  129. return st2 is XsdPositiveInteger || t == typeof (XsdDecimal) ||
  130. t == typeof (XsdInteger) || t == typeof (XsdNonNegativeInteger);
  131. else if (st1 is XsdUnsignedLong)
  132. return st2 is XsdUnsignedLong || t == typeof (XsdDecimal) ||
  133. t == typeof (XsdInteger) || t == typeof (XsdNonNegativeInteger);
  134. else if (st1 is XsdNonNegativeInteger)
  135. return st2 is XsdNonNegativeInteger || t == typeof (XsdDecimal) || t == typeof (XsdInteger);
  136. else if (st1 is XsdLong)
  137. return st2 is XsdLong || t == typeof (XsdDecimal) || t == typeof (XsdInteger);
  138. return true;
  139. }
  140. else if (!v1.Equals (v2))
  141. return false;
  142. if (st1 is XsdString) {
  143. if (!(st2 is XsdString))
  144. return false;
  145. if (st1 is XsdNMToken && (st2 is XsdLanguage || st2 is XsdName))
  146. return false;
  147. if (st2 is XsdNMToken && (st1 is XsdLanguage || st1 is XsdName))
  148. return false;
  149. if (st1 is XsdName && (st2 is XsdLanguage || st2 is XsdNMToken))
  150. return false;
  151. if (st2 is XsdName && (st1 is XsdLanguage || st1 is XsdNMToken))
  152. return false;
  153. if (st1 is XsdID && st2 is XsdIDRef)
  154. return false;
  155. if (st1 is XsdIDRef && st2 is XsdID)
  156. return false;
  157. }
  158. else if (st1 != st2)
  159. return false;
  160. return true;
  161. }
  162. public static bool IsValidQName(string qname)
  163. {
  164. foreach(string part in qname.Split(new char[]{':'},2))
  165. {
  166. if(!CheckNCName(part))
  167. return false;
  168. }
  169. return true;
  170. }
  171. //FIXME: First remove all the multiple instances of whitespace and then return the strings.
  172. //The current method returns empty strings if there are two or more consecutive whitespaces.
  173. public static string[] SplitList(string list)
  174. {
  175. if(list == null || list == string.Empty)
  176. return new string [0];
  177. string[] listarr = list.Split(new char[]{' ','\t','\n'});
  178. int pos=0;
  179. int i = 0;
  180. for(i=0;i<listarr.Length;i++)
  181. {
  182. if(listarr[i] != null && listarr[i] != String.Empty)
  183. {
  184. listarr[pos++] = listarr[i];
  185. }
  186. }
  187. if(pos == i)
  188. return listarr;
  189. string[] retarr = new String[pos];
  190. if(pos!=0)
  191. Array.Copy(listarr, retarr, pos);
  192. return retarr;
  193. }
  194. public static void ReadUnhandledAttribute(XmlReader reader, XmlSchemaObject xso)
  195. {
  196. if(reader.Prefix == "xmlns")
  197. xso.Namespaces.Add(reader.LocalName, reader.Value);
  198. else if(reader.Name == "xmlns")
  199. xso.Namespaces.Add("",reader.Value);
  200. else
  201. {
  202. if(xso.unhandledAttributeList == null)
  203. xso.unhandledAttributeList = new System.Collections.ArrayList();
  204. XmlAttribute attr = new XmlDocument().CreateAttribute(reader.LocalName,reader.NamespaceURI);
  205. attr.Value = reader.Value;
  206. ParseWsdlArrayType (reader, attr);
  207. xso.unhandledAttributeList.Add(attr);
  208. }
  209. }
  210. static void ParseWsdlArrayType (XmlReader reader, XmlAttribute attr)
  211. {
  212. if (attr.NamespaceURI == XmlSerializer.WsdlNamespace && attr.LocalName == "arrayType")
  213. {
  214. string ns = "", type, dimensions;
  215. TypeTranslator.ParseArrayType (attr.Value, out type, out ns, out dimensions);
  216. if (ns != "") ns = reader.LookupNamespace (ns) + ":";
  217. attr.Value = ns + type + dimensions;
  218. }
  219. }
  220. public static bool ReadBoolAttribute(XmlReader reader, out Exception innerExcpetion)
  221. {
  222. innerExcpetion = null;
  223. try
  224. {
  225. bool val = XmlConvert.ToBoolean(reader.Value);
  226. return val;
  227. }
  228. catch(Exception ex)
  229. {
  230. innerExcpetion = ex;
  231. return false;
  232. }
  233. }
  234. public static decimal ReadDecimalAttribute(XmlReader reader, out Exception innerExcpetion)
  235. {
  236. innerExcpetion = null;
  237. try
  238. {
  239. decimal val = XmlConvert.ToDecimal(reader.Value);
  240. return val;
  241. }
  242. catch(Exception ex)
  243. {
  244. innerExcpetion = ex;
  245. return decimal.Zero;
  246. }
  247. }
  248. // Is some value is read, return it.
  249. // If no values return empty.
  250. // If exception, return none
  251. public static XmlSchemaDerivationMethod ReadDerivationAttribute(XmlReader reader, out Exception innerExcpetion, string name, XmlSchemaDerivationMethod allowed)
  252. {
  253. innerExcpetion = null;
  254. try
  255. {
  256. string list = reader.Value;
  257. string warn = "";
  258. XmlSchemaDerivationMethod val = 0;
  259. if(list.IndexOf("#all") != -1 && list.Trim() != "#all")
  260. {
  261. innerExcpetion = new Exception(list+" is not a valid value for "+ name +". #all if present must be the only value");
  262. return XmlSchemaDerivationMethod.All;
  263. }
  264. foreach(string xsdm in XmlSchemaUtil.SplitList(list))
  265. {
  266. switch(xsdm)
  267. {
  268. case "":
  269. val = AddFlag (val, XmlSchemaDerivationMethod.Empty, allowed); break;
  270. case "#all":
  271. val = AddFlag (val,XmlSchemaDerivationMethod.All, allowed); break;
  272. case "substitution":
  273. val = AddFlag (val,XmlSchemaDerivationMethod.Substitution, allowed); break;
  274. case "extension":
  275. val = AddFlag (val,XmlSchemaDerivationMethod.Extension, allowed); break;
  276. case "restriction":
  277. val = AddFlag (val,XmlSchemaDerivationMethod.Restriction, allowed); break;
  278. case "list":
  279. val = AddFlag (val,XmlSchemaDerivationMethod.List, allowed); break;
  280. case "union":
  281. val = AddFlag (val,XmlSchemaDerivationMethod.Union, allowed); break;
  282. default:
  283. warn += xsdm + " "; break;
  284. }
  285. }
  286. if(warn != "")
  287. innerExcpetion = new Exception(warn + "is/are not valid values for " + name);
  288. return val;
  289. }
  290. catch(Exception ex)
  291. {
  292. innerExcpetion = ex;
  293. return XmlSchemaDerivationMethod.None;
  294. }
  295. }
  296. private static XmlSchemaDerivationMethod AddFlag (XmlSchemaDerivationMethod dst,
  297. XmlSchemaDerivationMethod add, XmlSchemaDerivationMethod allowed)
  298. {
  299. if ((add & allowed) == 0 && allowed != XmlSchemaDerivationMethod.All)
  300. throw new ArgumentException (add + " is not allowed in this attribute.");
  301. if ((dst & add) != 0)
  302. throw new ArgumentException (add + " is already specified in this attribute.");
  303. return dst | add;
  304. }
  305. public static XmlSchemaForm ReadFormAttribute(XmlReader reader, out Exception innerExcpetion)
  306. {
  307. innerExcpetion = null;
  308. XmlSchemaForm val = XmlSchemaForm.None;
  309. switch(reader.Value)
  310. {
  311. case "qualified":
  312. val = XmlSchemaForm.Qualified; break;
  313. case "unqualified":
  314. val = XmlSchemaForm.Unqualified; break;
  315. default:
  316. innerExcpetion = new Exception("only qualified or unqulified is a valid value"); break;
  317. }
  318. return val;
  319. }
  320. public static XmlSchemaContentProcessing ReadProcessingAttribute(XmlReader reader, out Exception innerExcpetion)
  321. {
  322. innerExcpetion = null;
  323. XmlSchemaContentProcessing val = XmlSchemaContentProcessing.None;
  324. switch(reader.Value)
  325. {
  326. case "lax":
  327. val = XmlSchemaContentProcessing.Lax; break;
  328. case "strict":
  329. val = XmlSchemaContentProcessing.Strict; break;
  330. case "skip":
  331. val = XmlSchemaContentProcessing.Skip; break;
  332. default:
  333. innerExcpetion = new Exception("only lax , strict or skip are valid values for processContents");
  334. break;
  335. }
  336. return val;
  337. }
  338. public static XmlSchemaUse ReadUseAttribute(XmlReader reader, out Exception innerExcpetion)
  339. {
  340. innerExcpetion = null;
  341. XmlSchemaUse val = XmlSchemaUse.None;
  342. switch(reader.Value)
  343. {
  344. case "optional":
  345. val = XmlSchemaUse.Optional; break;
  346. case "prohibited":
  347. val = XmlSchemaUse.Prohibited; break;
  348. case "required":
  349. val = XmlSchemaUse.Required; break;
  350. default:
  351. innerExcpetion = new Exception("only optional , prohibited or required are valid values for use");
  352. break;
  353. }
  354. return val;
  355. }
  356. public static XmlQualifiedName ReadQNameAttribute(XmlReader reader, out Exception innerEx)
  357. {
  358. return ToQName(reader, reader.Value, out innerEx);
  359. }
  360. //While Creating a XmlQualifedName, we should check:
  361. // 1. If a prefix is present, its namespace should be resolvable.
  362. // 2. If a prefix is not present, and if the defaultNamespace is set,
  363. public static XmlQualifiedName ToQName(XmlReader reader, string qnamestr, out Exception innerEx)
  364. {
  365. string ns;
  366. string name;
  367. XmlQualifiedName qname;
  368. innerEx = null;
  369. if(!IsValidQName(qnamestr))
  370. {
  371. innerEx = new Exception(qnamestr + " is an invalid QName. Either name or namespace is not a NCName");
  372. return XmlQualifiedName.Empty;
  373. }
  374. string[] values = qnamestr.Split(new char[]{':'},2);
  375. if(values.Length == 2)
  376. {
  377. ns = reader.LookupNamespace(values[0]);
  378. if(ns == null)
  379. {
  380. innerEx = new Exception("Namespace Prefix '"+values[0]+"could not be resolved");
  381. return XmlQualifiedName.Empty;
  382. }
  383. name = values[1];
  384. }
  385. else
  386. {
  387. //Default Namespace
  388. ns = reader.LookupNamespace("");
  389. name = values[0];
  390. }
  391. qname = new XmlQualifiedName(name,ns);
  392. return qname;
  393. }
  394. public static int ValidateAttributesResolved (
  395. XmlSchemaObjectTable attributesResolved,
  396. ValidationEventHandler h,
  397. XmlSchema schema,
  398. XmlSchemaObjectCollection attributes,
  399. XmlSchemaAnyAttribute anyAttribute,
  400. ref XmlSchemaAnyAttribute anyAttributeUse,
  401. XmlSchemaAttributeGroup redefined)
  402. {
  403. int errorCount = 0;
  404. if (anyAttribute != null && anyAttributeUse == null)
  405. anyAttributeUse = anyAttribute;
  406. foreach (XmlSchemaObject xsobj in attributes) {
  407. XmlSchemaAttributeGroupRef grpRef = xsobj as XmlSchemaAttributeGroupRef;
  408. if (grpRef != null) {
  409. // Resolve attributeGroup redefinition.
  410. XmlSchemaAttributeGroup grp = null;
  411. if (redefined != null && grpRef.RefName == redefined.QualifiedName)
  412. grp = redefined;
  413. else
  414. grp = schema.AttributeGroups [grpRef.RefName] as XmlSchemaAttributeGroup;
  415. // otherwise, it might be missing sub components.
  416. if (grp == null) {
  417. if (!schema.missedSubComponents)// && schema.Schemas [grpRef.RefName.Namespace] != null)
  418. grpRef.error (h, "Referenced attribute group " + grpRef.RefName + " was not found in the corresponding schema.");
  419. continue;
  420. }
  421. if (grp.AttributeGroupRecursionCheck) {
  422. grp.error (h, "Attribute group recursion was found: " + grpRef.RefName);
  423. continue;
  424. }
  425. try {
  426. grp.AttributeGroupRecursionCheck = true;
  427. errorCount += grp.Validate (h, schema);
  428. } finally {
  429. grp.AttributeGroupRecursionCheck = false;
  430. }
  431. if (grp.AnyAttributeUse != null) {
  432. // FIXME: should validate wildcard subset validity. See spec 3.10.6
  433. if (anyAttribute == null)
  434. anyAttributeUse = grp.AnyAttributeUse;
  435. }
  436. foreach (DictionaryEntry entry in grp.AttributeUses) {
  437. XmlSchemaAttribute attr = (XmlSchemaAttribute) entry.Value;
  438. if (attr.RefName != null && attr.RefName != XmlQualifiedName.Empty)
  439. AddToTable (attributesResolved, attr, attr.RefName, h);
  440. else
  441. AddToTable (attributesResolved, attr, attr.QualifiedName, h);
  442. }
  443. } else {
  444. XmlSchemaAttribute attr = xsobj as XmlSchemaAttribute;
  445. if (attr != null) {
  446. errorCount += attr.Validate (h, schema);
  447. if (attr.RefName != null && attr.RefName != XmlQualifiedName.Empty)
  448. AddToTable (attributesResolved, attr, attr.RefName, h);
  449. else
  450. AddToTable (attributesResolved, attr, attr.QualifiedName, h);
  451. } else {
  452. if (anyAttribute == null) {
  453. anyAttributeUse = (XmlSchemaAnyAttribute) xsobj;
  454. anyAttribute.Validate (h, schema);
  455. }
  456. }
  457. }
  458. }
  459. return errorCount;
  460. }
  461. }
  462. }