XmlSchemaInference.cs 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. //
  2. // XmlSchemaInference.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C)2004 Novell Inc.
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. #if NET_2_0
  30. using System;
  31. using System.Collections;
  32. using System.Xml;
  33. using System.Xml.Schema;
  34. using QName = System.Xml.XmlQualifiedName;
  35. using Form = System.Xml.Schema.XmlSchemaForm;
  36. using Use = System.Xml.Schema.XmlSchemaUse;
  37. using SOMList = System.Xml.Schema.XmlSchemaObjectCollection;
  38. using SOMObject = System.Xml.Schema.XmlSchemaObject;
  39. using Element = System.Xml.Schema.XmlSchemaElement;
  40. using Attr = System.Xml.Schema.XmlSchemaAttribute;
  41. using AttrGroup = System.Xml.Schema.XmlSchemaAttributeGroup;
  42. using AttrGroupRef = System.Xml.Schema.XmlSchemaAttributeGroupRef;
  43. using SimpleType = System.Xml.Schema.XmlSchemaSimpleType;
  44. using ComplexType = System.Xml.Schema.XmlSchemaComplexType;
  45. using SimpleModel = System.Xml.Schema.XmlSchemaSimpleContent;
  46. using SimpleExt = System.Xml.Schema.XmlSchemaSimpleContentExtension;
  47. using SimpleRst = System.Xml.Schema.XmlSchemaSimpleContentRestriction;
  48. using ComplexModel = System.Xml.Schema.XmlSchemaComplexContent;
  49. using ComplexExt = System.Xml.Schema.XmlSchemaComplexContentExtension;
  50. using ComplexRst = System.Xml.Schema.XmlSchemaComplexContentRestriction;
  51. using SimpleTypeRst = System.Xml.Schema.XmlSchemaSimpleTypeRestriction;
  52. using SimpleList = System.Xml.Schema.XmlSchemaSimpleTypeList;
  53. using SimpleUnion = System.Xml.Schema.XmlSchemaSimpleTypeUnion;
  54. using SchemaFacet = System.Xml.Schema.XmlSchemaFacet;
  55. using LengthFacet = System.Xml.Schema.XmlSchemaLengthFacet;
  56. using MinLengthFacet = System.Xml.Schema.XmlSchemaMinLengthFacet;
  57. using Particle = System.Xml.Schema.XmlSchemaParticle;
  58. using Sequence = System.Xml.Schema.XmlSchemaSequence;
  59. using Choice = System.Xml.Schema.XmlSchemaChoice;
  60. namespace System.Xml.Schema
  61. {
  62. public class XmlSchemaInference
  63. {
  64. public enum InferenceOption {
  65. Relaxed,
  66. Rstricted
  67. }
  68. InferenceOption occurrence = InferenceOption.Rstricted;
  69. InferenceOption typeInference = InferenceOption.Rstricted;
  70. public XmlSchemaInference ()
  71. {
  72. }
  73. public InferenceOption Occurrence {
  74. get { return occurrence; }
  75. set { occurrence = value; }
  76. }
  77. public InferenceOption TypeInference {
  78. get { return TypeInference; }
  79. set { typeInference = value; }
  80. }
  81. public XmlSchemaSet InferSchema (XmlReader xmlReader)
  82. {
  83. return InferSchema (xmlReader, new XmlSchemaSet ());
  84. }
  85. public XmlSchemaSet InferSchema (XmlReader xmlReader, XmlSchemaSet schemas)
  86. {
  87. return XsdInference.Process (xmlReader, schemas,
  88. occurrence == InferenceOption.Relaxed,
  89. typeInference == InferenceOption.Relaxed);
  90. }
  91. }
  92. class XsdInference
  93. {
  94. public static XmlSchemaSet Process (XmlReader xmlReader, XmlSchemaSet schemas, bool laxOccurence, bool laxTypeInference)
  95. {
  96. XsdInference impl = new XsdInference (xmlReader,
  97. schemas, laxOccurence, laxTypeInference);
  98. impl.Run ();
  99. return impl.schemas;
  100. }
  101. public const string NamespaceXml = "http://www.w3.org/XML/1998/namespace";
  102. public const string NamespaceXmlns = "http://www.w3.org/2000/xmlns/";
  103. public const string XdtNamespace = "http://www.w3.org/2003/11/xpath-datatypes";
  104. static readonly QName QNameString = new QName ("string",
  105. XmlSchema.Namespace);
  106. static readonly QName QNameBoolean = new QName ("boolean",
  107. XmlSchema.Namespace);
  108. static readonly QName QNameAnyType = new QName ("anyType",
  109. XmlSchema.Namespace);
  110. XmlReader source;
  111. XmlSchemaSet schemas;
  112. bool laxOccurence;
  113. bool laxTypeInference;
  114. Hashtable newElements = new Hashtable ();
  115. Hashtable newAttributes = new Hashtable ();
  116. private XsdInference (XmlReader xmlReader, XmlSchemaSet schemas, bool laxOccurence, bool laxTypeInference)
  117. {
  118. this.source = xmlReader;
  119. this.schemas = schemas;
  120. this.laxOccurence = laxOccurence;
  121. this.laxTypeInference = laxTypeInference;
  122. }
  123. private void Run ()
  124. {
  125. // XmlSchemaSet need to be compiled.
  126. schemas.Compile ();
  127. // move to top-level element
  128. source.MoveToContent ();
  129. int depth = source.Depth;
  130. if (source.NodeType != XmlNodeType.Element)
  131. throw new ArgumentException ("Argument XmlReader content is expected to be an element.");
  132. QName qname = new QName (source.LocalName,
  133. source.NamespaceURI);
  134. Element el = GetGlobalElement (qname);
  135. if (el == null) {
  136. el = CreateGlobalElement (qname);
  137. InferElement (el, qname.Namespace, true);
  138. }
  139. else
  140. InferElement (el, qname.Namespace, false);
  141. }
  142. private void IncludeXmlAttributes ()
  143. {
  144. if (schemas.Schemas (NamespaceXml).Count == 0)
  145. // FIXME: do it from resources.
  146. schemas.Add (NamespaceXml, "http://www.w3.org/2001/xml.xsd");
  147. }
  148. private void InferElement (Element el, string ns, bool isNew)
  149. {
  150. // Quick check for reference to another definition
  151. // (i.e. element ref='...' that should be redirected)
  152. if (el.RefName != QName.Empty) {
  153. Element body = GetGlobalElement (el.RefName);
  154. if (body == null) {
  155. body = CreateElement (el.RefName);
  156. InferElement (body, ns, true);
  157. }
  158. else
  159. InferElement (body, ns, isNew);
  160. return;
  161. }
  162. // Attributes
  163. if (source.MoveToFirstAttribute ()) {
  164. InferAttributes (el, ns, isNew);
  165. source.MoveToElement ();
  166. }
  167. // Content
  168. if (source.IsEmptyElement) {
  169. InferAsEmptyElement (el, ns, isNew);
  170. source.Read ();
  171. source.MoveToContent ();
  172. }
  173. else {
  174. InferContent (el, ns, isNew);
  175. source.ReadEndElement ();
  176. }
  177. if (el.SchemaType == null &&
  178. el.SchemaTypeName == QName.Empty)
  179. el.SchemaTypeName = QNameString;
  180. }
  181. #region Attribute Inference
  182. private Hashtable CollectAttrTable (SOMList attList)
  183. {
  184. // get attribute definition table.
  185. Hashtable table = new Hashtable ();
  186. foreach (XmlSchemaObject obj in attList) {
  187. Attr attr = obj as Attr;
  188. if (attr == null)
  189. throw Error (obj, String.Format ("Attribute inference only supports direct attribute definition. {0} is not supported.", obj.GetType ()));
  190. if (attr.RefName != QName.Empty)
  191. table.Add (attr.RefName, attr);
  192. else
  193. table.Add (new QName (attr.Name, ""),
  194. attr);
  195. }
  196. return table;
  197. }
  198. private void InferAttributes (Element el, string ns, bool isNew)
  199. {
  200. // Now this element is going to have complexType.
  201. // It currently not, then we have to replace it.
  202. ComplexType ct = null;
  203. SOMList attList = null;
  204. Hashtable table = null;
  205. do {
  206. switch (source.NamespaceURI) {
  207. case NamespaceXml:
  208. if (schemas.Schemas (
  209. NamespaceXml) .Count == 0)
  210. IncludeXmlAttributes ();
  211. break;
  212. case XmlSchema.InstanceNamespace:
  213. if (source.LocalName == "nil")
  214. el.IsNillable = true;
  215. // all other xsi:* atts are ignored
  216. continue;
  217. case NamespaceXmlns:
  218. continue;
  219. }
  220. if (ct == null) {
  221. ct = ToComplexType (el);
  222. attList = GetAttributes (ct);
  223. table = CollectAttrTable (attList);
  224. }
  225. QName attrName = new QName (
  226. source.LocalName, source.NamespaceURI);
  227. Attr attr = table [attrName] as Attr;
  228. if (attr == null) {
  229. attList.Add (InferNewAttribute (
  230. attrName, isNew));
  231. } else {
  232. table.Remove (attrName);
  233. if (attr.RefName != null &&
  234. attr.RefName != QName.Empty)
  235. continue; // just a reference
  236. InferMergedAttribute (attr);
  237. }
  238. } while (source.MoveToNextAttribute ());
  239. // mark all attr definitions that did not appear
  240. // as optional.
  241. if (table != null)
  242. foreach (Attr attr in table.Values)
  243. attr.Use = Use.Optional;
  244. }
  245. private XmlSchemaAttribute InferNewAttribute (
  246. QName attrName, bool isNewTypeDefinition)
  247. {
  248. Attr attr = null;
  249. bool mergedRequired = false;
  250. if (attrName.Namespace.Length > 0) {
  251. // global attribute; might be already defined.
  252. attr = GetGlobalAttribute (attrName) as Attr;
  253. if (attr == null) {
  254. attr = CreateGlobalAttribute (attrName);
  255. attr.SchemaTypeName =
  256. InferSimpleType (source.Value);
  257. } else {
  258. InferMergedAttribute (attr);
  259. mergedRequired =
  260. attr.Use == Use.Required;
  261. }
  262. attr = new Attr ();
  263. attr.RefName = attrName;
  264. } else {
  265. // local attribute
  266. attr = new Attr ();
  267. attr.Name = attrName.Name;
  268. attr.SchemaTypeName =
  269. InferSimpleType (source.Value);
  270. }
  271. if (!laxOccurence &&
  272. (isNewTypeDefinition || mergedRequired))
  273. attr.Use = Use.Required;
  274. else
  275. attr.Use = Use.Optional;
  276. return attr;
  277. }
  278. // validate string value agains attr and
  279. // if invalid, then relax the type.
  280. private void InferMergedAttribute (Attr attr)
  281. {
  282. attr.SchemaTypeName = InferMergedType (source.Value,
  283. attr.SchemaTypeName);
  284. attr.SchemaType = null;
  285. }
  286. private QName InferMergedType (string value, QName typeName)
  287. {
  288. // examine value against specified type and
  289. // if unacceptable, then return a relaxed type.
  290. SimpleType st = XmlSchemaType.GetBuiltInSimpleType (
  291. typeName);
  292. if (st == null) // non-primitive type => see above.
  293. return QNameString;
  294. try {
  295. st.Datatype.ParseValue (value,
  296. source.NameTable,
  297. source as IXmlNamespaceResolver);
  298. // the string value was value
  299. return typeName;
  300. } catch {
  301. // The types were incompatible.
  302. // FIXME: find the base common type
  303. return QNameString;
  304. }
  305. }
  306. private SOMList GetAttributes (ComplexType ct)
  307. {
  308. if (ct.ContentModel == null)
  309. return ct.Attributes;
  310. SimpleModel sc = ct.ContentModel as SimpleModel;
  311. if (sc != null) {
  312. SimpleExt sce = sc.Content as SimpleExt;
  313. if (sce != null)
  314. return sce.Attributes;
  315. SimpleRst scr = sc.Content as SimpleRst;
  316. if (scr != null)
  317. return scr.Attributes;
  318. else
  319. throw Error (sc, "Invalid simple content model.");
  320. }
  321. ComplexModel cc = ct.ContentModel as ComplexModel;
  322. if (cc != null) {
  323. ComplexExt cce = cc.Content as ComplexExt;
  324. if (cce != null)
  325. return cce.Attributes;
  326. ComplexRst ccr = cc.Content as ComplexRst;
  327. if (ccr != null)
  328. return ccr.Attributes;
  329. else
  330. throw Error (cc, "Invalid simple content model.");
  331. }
  332. throw Error (cc, "Invalid complexType. Should not happen.");
  333. }
  334. private ComplexType ToComplexType (Element el)
  335. {
  336. QName name = el.SchemaTypeName;
  337. XmlSchemaType type = el.SchemaType;
  338. // 1. element type is complex.
  339. ComplexType ct = type as ComplexType;
  340. if (ct != null)
  341. return ct;
  342. // 2. reference to global complexType.
  343. XmlSchemaType globalType = schemas.GlobalTypes [name]
  344. as XmlSchemaType;
  345. ct = globalType as ComplexType;
  346. if (ct != null)
  347. return ct;
  348. ct = new ComplexType ();
  349. el.SchemaType = ct;
  350. el.SchemaTypeName = QName.Empty;
  351. // 3. base type name is xs:anyType or no specification.
  352. // <xs:complexType />
  353. if (name == QNameAnyType)
  354. return ct;
  355. else if (type == null && name == QName.Empty)
  356. return ct;
  357. SimpleModel sc = new SimpleModel ();
  358. ct.ContentModel = sc;
  359. // 4. type is simpleType
  360. // -> extension of existing simple type.
  361. SimpleType st = type as SimpleType;
  362. if (st != null) {
  363. SimpleRst scr = new SimpleRst ();
  364. scr.BaseType = st;
  365. sc.Content = scr;
  366. return ct;
  367. }
  368. SimpleExt sce = new SimpleExt ();
  369. sc.Content = sce;
  370. // 5. type name points to primitive type
  371. // -> simple extension of a primitive type
  372. st = XmlSchemaType.GetBuiltInSimpleType (name);
  373. if (st != null) {
  374. sce.BaseTypeName = name;
  375. return ct;
  376. }
  377. // 6. type name points to global simpleType.
  378. st = globalType as SimpleType;
  379. if (st != null) {
  380. sce.BaseTypeName = name;
  381. return ct;
  382. }
  383. throw Error (el, "Unexpected schema component that contains simpleTypeName that could not be resolved.");
  384. }
  385. #endregion
  386. #region Element Type
  387. private void InferAsEmptyElement (Element el, string ns,
  388. bool isNew)
  389. {
  390. ComplexType ct = el.SchemaType as ComplexType;
  391. if (ct != null) {
  392. SimpleModel sm =
  393. ct.ContentModel as SimpleModel;
  394. if (sm != null) {
  395. ToEmptiableSimpleContent (sm, isNew);
  396. return;
  397. }
  398. ComplexModel cm = ct.ContentModel
  399. as ComplexModel;
  400. if (cm != null) {
  401. ToEmptiableComplexContent (cm, isNew);
  402. return;
  403. }
  404. if (ct.Particle != null)
  405. ct.Particle.MinOccurs = 0;
  406. return;
  407. }
  408. SimpleType st = el.SchemaType as SimpleType;
  409. if (st != null) {
  410. st = MakeBaseTypeAsEmptiable (st);
  411. switch (st.QualifiedName.Namespace) {
  412. case XmlSchema.Namespace:
  413. case XdtNamespace:
  414. el.SchemaTypeName = st.QualifiedName;
  415. break;
  416. default:
  417. el.SchemaType =st;
  418. break;
  419. }
  420. }
  421. }
  422. private SimpleType MakeBaseTypeAsEmptiable (SimpleType st)
  423. {
  424. switch (st.QualifiedName.Namespace) {
  425. case XmlSchema.Namespace:
  426. case XdtNamespace:
  427. // If a primitive type
  428. return XmlSchemaType.GetBuiltInSimpleType (
  429. XmlTypeCode.String);
  430. }
  431. SimpleTypeRst str = st.Content as SimpleTypeRst;
  432. if (str != null) {
  433. ArrayList al = null;
  434. foreach (SchemaFacet f in str.Facets) {
  435. if (f is LengthFacet ||
  436. f is MinLengthFacet) {
  437. if (al == null)
  438. al = new ArrayList ();
  439. al.Add (f);
  440. }
  441. }
  442. foreach (SchemaFacet f in al)
  443. str.Facets.Remove (f);
  444. if (str.BaseType != null)
  445. str.BaseType =
  446. MakeBaseTypeAsEmptiable (st);
  447. else
  448. // It might have a reference to an
  449. // external simple type, but there is
  450. // no assurance that any of those
  451. // external types allow an empty
  452. // string. So just set base type as
  453. // xs:string.
  454. str.BaseTypeName = QNameString;
  455. } // union/list can have empty string value.
  456. return st;
  457. }
  458. private void ToEmptiableSimpleContent (
  459. SimpleModel sm, bool isNew)
  460. {
  461. SimpleExt se = sm.Content as SimpleExt;
  462. if (se != null)
  463. se.BaseTypeName = QNameString;
  464. else {
  465. SimpleRst sr = sm.Content
  466. as SimpleRst;
  467. if (sr == null)
  468. throw Error (sm, "Invalid simple content model was passed.");
  469. sr.BaseTypeName = QNameString;
  470. sr.BaseType = null;
  471. }
  472. }
  473. private void ToEmptiableComplexContent (
  474. ComplexModel cm, bool isNew)
  475. {
  476. ComplexExt ce = cm.Content
  477. as ComplexExt;
  478. if (ce != null) {
  479. if (ce.Particle != null)
  480. ce.Particle.MinOccurs = 0;
  481. else if (ce.BaseTypeName != null &&
  482. ce.BaseTypeName != QName.Empty &&
  483. ce.BaseTypeName != QNameAnyType)
  484. throw Error (ce, "Complex type content extension has a reference to an external component that is not supported.");
  485. }
  486. else {
  487. ComplexRst cr = cm.Content
  488. as ComplexRst;
  489. if (cr == null)
  490. throw Error (cm, "Invalid complex content model was passed.");
  491. if (cr.Particle != null)
  492. cr.Particle.MinOccurs = 0;
  493. else if (cr.BaseTypeName != null &&
  494. cr.BaseTypeName != QName.Empty &&
  495. cr.BaseTypeName != QNameAnyType)
  496. throw Error (cr, "Complex type content extension has a reference to an external component that is not supported.");
  497. }
  498. }
  499. private void InferContent (Element el, string ns, bool isNew)
  500. {
  501. source.Read ();
  502. source.MoveToContent ();
  503. switch (source.NodeType) {
  504. case XmlNodeType.EndElement:
  505. InferAsEmptyElement (el, ns, isNew);
  506. break;
  507. case XmlNodeType.Element:
  508. InferComplexContent (el, ns, isNew);
  509. break;
  510. case XmlNodeType.Text:
  511. case XmlNodeType.CDATA:
  512. case XmlNodeType.SignificantWhitespace:
  513. InferTextContent (el, isNew);
  514. source.MoveToContent ();
  515. if (source.NodeType == XmlNodeType.Element)
  516. goto case XmlNodeType.Element;
  517. break;
  518. case XmlNodeType.Whitespace:
  519. InferContent (el, ns, isNew); // skip and retry
  520. break;
  521. }
  522. }
  523. private void InferComplexContent (Element el, string ns,
  524. bool isNew)
  525. {
  526. ComplexType ct = ToComplexType (el);
  527. ToComplexContentType (ct);
  528. int position = 0;
  529. bool consumed = false;
  530. do {
  531. switch (source.NodeType) {
  532. case XmlNodeType.Element:
  533. Sequence s = PopulateSequence (ct);
  534. Choice c = s.Items.Count > 0 ?
  535. s.Items [0] as Choice :
  536. null;
  537. if (c != null)
  538. ProcessLax (c, ns);
  539. else
  540. ProcessSequence (ct, s, ns,
  541. ref position,
  542. ref consumed,
  543. isNew);
  544. source.MoveToContent ();
  545. break;
  546. case XmlNodeType.Text:
  547. case XmlNodeType.CDATA:
  548. case XmlNodeType.SignificantWhitespace:
  549. MarkAsMixed (ct);
  550. source.ReadString ();
  551. source.MoveToContent ();
  552. break;
  553. case XmlNodeType.EndElement:
  554. return; // finished
  555. case XmlNodeType.None:
  556. throw new NotImplementedException ("Internal Error: Should not happen.");
  557. }
  558. } while (true);
  559. }
  560. private void InferTextContent (Element el, bool isNew)
  561. {
  562. string value = source.ReadString ();
  563. if (el.SchemaType == null) {
  564. if (el.SchemaTypeName == QName.Empty) {
  565. // no type information -> infer type
  566. if (isNew)
  567. el.SchemaTypeName =
  568. InferSimpleType (
  569. value);
  570. else
  571. el.SchemaTypeName =
  572. QNameString;
  573. return;
  574. }
  575. switch (el.SchemaTypeName.Namespace) {
  576. case XmlSchema.Namespace:
  577. case XdtNamespace:
  578. // existing primitive type
  579. el.SchemaTypeName = InferMergedType (
  580. value, el.SchemaTypeName);
  581. break;
  582. default:
  583. ComplexType ct = schemas.GlobalTypes [
  584. el.SchemaTypeName]
  585. as ComplexType;
  586. // If it is complex, then just set
  587. // mixed='true' (type cannot be set.)
  588. // If it is simple, then we cannot
  589. // make sure that string value is
  590. // valid. So just set as xs:string.
  591. if (ct != null)
  592. MarkAsMixed (ct);
  593. else
  594. el.SchemaTypeName = QNameString;
  595. break;
  596. }
  597. return;
  598. }
  599. // simpleType
  600. SimpleType st = el.SchemaType as SimpleType;
  601. if (st != null) {
  602. // If simple, then (described above)
  603. el.SchemaType = null;
  604. el.SchemaTypeName = QNameString;
  605. return;
  606. }
  607. // complexType
  608. ComplexType ect = el.SchemaType as ComplexType;
  609. SimpleModel sm = ect.ContentModel as SimpleModel;
  610. if (sm == null) {
  611. // - ComplexContent
  612. MarkAsMixed (ect);
  613. return;
  614. }
  615. // - SimpleContent
  616. SimpleExt se = sm.Content as SimpleExt;
  617. if (se != null)
  618. se.BaseTypeName = InferMergedType (value,
  619. se.BaseTypeName);
  620. SimpleRst sr = sm.Content as SimpleRst;
  621. if (sr != null) {
  622. sr.BaseTypeName = InferMergedType (value,
  623. sr.BaseTypeName);
  624. sr.BaseType = null;
  625. }
  626. }
  627. private void MarkAsMixed (ComplexType ct)
  628. {
  629. ComplexModel cm = ct.ContentModel as ComplexModel;
  630. if (cm != null)
  631. cm.IsMixed = true;
  632. else
  633. ct.IsMixed = true;
  634. }
  635. #endregion
  636. #region Particles
  637. private void ProcessLax (Choice c, string ns)
  638. {
  639. foreach (Particle p in c.Items) {
  640. Element el = p as Element;
  641. if (el == null)
  642. throw Error (c, String.Format ("Target schema item contains unacceptable particle {0}. Only element is allowed here."));
  643. if (ElementMatches (el, ns)) {
  644. InferElement (el, ns, false);
  645. return;
  646. }
  647. }
  648. // append a new element particle to lax term.
  649. Element nel = new Element ();
  650. if (source.NamespaceURI == ns)
  651. nel.Name = source.LocalName;
  652. else
  653. nel.RefName = new QName (source.LocalName,
  654. source.NamespaceURI);
  655. InferElement (nel, source.NamespaceURI, true);
  656. c.Items.Add (nel);
  657. }
  658. private bool ElementMatches (Element el, string ns)
  659. {
  660. bool matches = false;
  661. if (el.RefName != QName.Empty) {
  662. if (el.RefName.Name == source.LocalName &&
  663. el.RefName.Namespace ==
  664. source.NamespaceURI)
  665. matches = true;
  666. }
  667. else if (el.Name == source.LocalName &&
  668. ns == source.NamespaceURI)
  669. matches = true;
  670. return matches;
  671. }
  672. private void ProcessSequence (ComplexType ct, Sequence s,
  673. string ns, ref int position, ref bool consumed,
  674. bool isNew)
  675. {
  676. for (int i = 0; i < position; i++) {
  677. Element iel = s.Items [i] as Element;
  678. if (ElementMatches (iel, ns)) {
  679. // Sequence element type violation
  680. // might happen (might not, but we
  681. // cannot backtrack here). So switch
  682. // to sequence of choice* here.
  683. ProcessLax (ToSequenceOfChoice (s), ns);
  684. return;
  685. }
  686. }
  687. if (s.Items.Count <= position) {
  688. QName name = new QName (source.LocalName,
  689. source.NamespaceURI);
  690. Element nel = CreateElement (name);
  691. InferElement (nel, ns, true);
  692. if (ns == name.Namespace)
  693. s.Items.Add (nel);
  694. else {
  695. Element re = new Element ();
  696. re.RefName = name;
  697. s.Items.Add (re);
  698. }
  699. consumed = true;
  700. return;
  701. }
  702. Element el = s.Items [position] as Element;
  703. if (el == null)
  704. throw Error (s, String.Format ("Target complex type content sequence has an unacceptable type of particle {0}", s.Items [position]));
  705. bool matches = ElementMatches (el, ns);
  706. if (matches) {
  707. if (consumed)
  708. el.MaxOccursString = "unbounded";
  709. InferElement (el, source.NamespaceURI, false);
  710. source.MoveToContent ();
  711. switch (source.NodeType) {
  712. case XmlNodeType.None:
  713. if (source.NodeType ==
  714. XmlNodeType.Element)
  715. goto case XmlNodeType.Element;
  716. else if (source.NodeType ==
  717. XmlNodeType.EndElement)
  718. goto case XmlNodeType.EndElement;
  719. break;
  720. case XmlNodeType.Element:
  721. ProcessSequence (ct, s, ns, ref position,
  722. ref consumed, isNew);
  723. break;
  724. case XmlNodeType.Text:
  725. case XmlNodeType.CDATA:
  726. case XmlNodeType.SignificantWhitespace:
  727. MarkAsMixed (ct);
  728. source.ReadString ();
  729. goto case XmlNodeType.None;
  730. case XmlNodeType.Whitespace:
  731. source.ReadString ();
  732. goto case XmlNodeType.None;
  733. case XmlNodeType.EndElement:
  734. return;
  735. default:
  736. source.Read ();
  737. break;
  738. }
  739. }
  740. else {
  741. if (consumed) {
  742. position++;
  743. consumed = false;
  744. ProcessSequence (ct, s, ns,
  745. ref position, ref consumed,
  746. isNew);
  747. }
  748. else
  749. ProcessLax (ToSequenceOfChoice (s), ns);
  750. }
  751. }
  752. // Note that it does not return the changed sequence.
  753. private Choice ToSequenceOfChoice (Sequence s)
  754. {
  755. Choice c = new Choice ();
  756. if (laxOccurence)
  757. c.MinOccurs = 0;
  758. c.MaxOccursString = "unbounded";
  759. foreach (Particle p in s.Items)
  760. c.Items.Add (p);
  761. s.Items.Clear ();
  762. s.Items.Add (c);
  763. return c;
  764. }
  765. // It makes complexType not to have Simple content model.
  766. private void ToComplexContentType (ComplexType type)
  767. {
  768. SimpleModel sm = type.ContentModel as SimpleModel;
  769. if (sm == null)
  770. return;
  771. SOMList atts = GetAttributes (type);
  772. foreach (SOMObject o in atts)
  773. type.Attributes.Add (o);
  774. // FIXME: need to copy AnyAttribute.
  775. // (though not considered right now)
  776. type.ContentModel = null;
  777. type.IsMixed = true;
  778. }
  779. private Sequence PopulateSequence (ComplexType ct)
  780. {
  781. Particle p = PopulateParticle (ct);
  782. Sequence s = p as Sequence;
  783. if (s != null)
  784. return s;
  785. else
  786. throw Error (ct, String.Format ("Target complexType contains unacceptable type of particle {0}", p));
  787. }
  788. private Sequence CreateSequence ()
  789. {
  790. Sequence s = new Sequence ();
  791. if (laxOccurence)
  792. s.MinOccurs = 0;
  793. return s;
  794. }
  795. private Particle PopulateParticle (ComplexType ct)
  796. {
  797. if (ct.ContentModel == null) {
  798. if (ct.Particle == null)
  799. ct.Particle = CreateSequence ();
  800. return ct.Particle;
  801. }
  802. ComplexModel cm = ct.ContentModel as ComplexModel;
  803. if (cm != null) {
  804. ComplexExt ce = cm.Content as ComplexExt;
  805. if (ce != null) {
  806. if (ce.Particle == null)
  807. ce.Particle = CreateSequence ();
  808. return ce.Particle;
  809. }
  810. ComplexRst cr = cm.Content as ComplexRst;
  811. if (cr != null) {
  812. if (cr.Particle == null)
  813. cr.Particle = CreateSequence ();
  814. return cr.Particle;
  815. }
  816. }
  817. throw Error (ct, "Schema inference internal error. The complexType should have been converted to have a complex content.");
  818. }
  819. #endregion
  820. #region String Value
  821. // primitive type inference.
  822. // When running lax type inference, it just returns xs:string.
  823. private QName InferSimpleType (string value)
  824. {
  825. if (laxTypeInference)
  826. return QNameString;
  827. switch (value) {
  828. // 0 and 1 are not infered as byte unlike MS.XSDInfer
  829. // case "0":
  830. // case "1":
  831. case "true":
  832. case "false":
  833. return QNameBoolean;
  834. }
  835. try {
  836. long dec = XmlConvert.ToInt64 (value);
  837. if (byte.MinValue <= dec && dec <= byte.MaxValue)
  838. return XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.UnsignedByte).QualifiedName;
  839. if (sbyte.MinValue <= dec && dec <= sbyte.MaxValue)
  840. return XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Byte).QualifiedName;
  841. if (ushort.MinValue <= dec && dec <= ushort.MaxValue)
  842. return XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.UnsignedShort).QualifiedName;
  843. if (short.MinValue <= dec && dec <= short.MaxValue)
  844. return XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Short).QualifiedName;
  845. if (uint.MinValue <= dec && dec <= uint.MaxValue)
  846. return XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.UnsignedInt).QualifiedName;
  847. if (int.MinValue <= dec && dec <= int.MaxValue)
  848. return XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Int).QualifiedName;
  849. return XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Long).QualifiedName;
  850. } catch (Exception) {
  851. }
  852. try {
  853. XmlConvert.ToUInt64 (value);
  854. return XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.UnsignedLong).QualifiedName;
  855. } catch (Exception) {
  856. }
  857. try {
  858. XmlConvert.ToDecimal (value);
  859. return XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Decimal).QualifiedName;
  860. } catch (Exception) {
  861. }
  862. try {
  863. double dbl = XmlConvert.ToDouble (value);
  864. if (float.MinValue <= dbl && dbl <= float.MaxValue)
  865. return XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Float).QualifiedName;
  866. else
  867. return XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Double).QualifiedName;
  868. } catch (Exception) {
  869. }
  870. try {
  871. // FIXME: also try DateTimeSerializationMode
  872. // and gYearMonth
  873. XmlConvert.ToDateTime (value);
  874. return XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.DateTime).QualifiedName;
  875. } catch (Exception) {
  876. }
  877. try {
  878. XmlConvert.ToTimeSpan (value);
  879. return XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Duration).QualifiedName;
  880. } catch (Exception) {
  881. }
  882. // xs:string
  883. return QNameString;
  884. }
  885. #endregion
  886. #region Utilities
  887. private Element GetGlobalElement (QName name)
  888. {
  889. Element el = newElements [name] as Element;
  890. if (el == null)
  891. el = schemas.GlobalElements [name] as Element;
  892. return el;
  893. }
  894. private Attr GetGlobalAttribute (QName name)
  895. {
  896. Attr a = newElements [name] as Attr;
  897. if (a == null)
  898. a = schemas.GlobalAttributes [name] as Attr;
  899. return a;
  900. }
  901. private Element CreateElement (QName name)
  902. {
  903. Element el = new Element ();
  904. el.Name = name.Name;
  905. return el;
  906. }
  907. private Element CreateGlobalElement (QName name)
  908. {
  909. Element el = CreateElement (name);
  910. XmlSchema schema = PopulateSchema (name.Namespace);
  911. schema.Items.Add (el);
  912. newElements.Add (name, el);
  913. return el;
  914. }
  915. private Attr CreateGlobalAttribute (QName name)
  916. {
  917. Attr attr = new Attr ();
  918. XmlSchema schema = PopulateSchema (name.Namespace);
  919. attr.Name = name.Name;
  920. schema.Items.Add (attr);
  921. newAttributes.Add (name, attr);
  922. return attr;
  923. }
  924. // Note that the return value never assures that all the
  925. // components in the parameter ns must reside in it.
  926. private XmlSchema PopulateSchema (string ns)
  927. {
  928. ICollection list = schemas.Schemas (ns);
  929. if (list.Count > 0) {
  930. IEnumerator e = list.GetEnumerator ();
  931. e.MoveNext ();
  932. return (XmlSchema) e.Current;
  933. }
  934. XmlSchema s = new XmlSchema ();
  935. if (ns != null && ns.Length > 0)
  936. s.TargetNamespace = ns;
  937. s.ElementFormDefault = Form.Qualified;
  938. s.AttributeFormDefault = Form.Unqualified;
  939. schemas.Add (s);
  940. return s;
  941. }
  942. private XmlSchemaInferenceException Error (
  943. XmlSchemaObject sourceObj,
  944. string message)
  945. {
  946. // This override is mainly for schema component error.
  947. return Error (sourceObj, false, message);
  948. }
  949. private XmlSchemaInferenceException Error (
  950. XmlSchemaObject sourceObj,
  951. bool useReader,
  952. string message)
  953. {
  954. string msg = String.Concat (
  955. message,
  956. sourceObj != null ?
  957. String.Format (". Related schema component is {0}",
  958. sourceObj.SourceUri,
  959. sourceObj.LineNumber,
  960. sourceObj.LinePosition) :
  961. String.Empty,
  962. useReader ?
  963. String.Format (". {0}", source.BaseURI) :
  964. String.Empty);
  965. IXmlLineInfo li = source as IXmlLineInfo;
  966. if (useReader && li != null)
  967. return new XmlSchemaInferenceException (
  968. msg, null, li.LineNumber,
  969. li.LinePosition);
  970. else
  971. return new XmlSchemaInferenceException (msg);
  972. }
  973. #endregion
  974. }
  975. }
  976. #endif