XmlSchemaUtil.cs 16 KB

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