XmlSchemaUtil.cs 16 KB

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