DTDValidatingReader.cs 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  1. //
  2. // DTDValidatingReader.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto ([email protected])
  6. //
  7. // (C)2003 Atsushi Enomoto
  8. // (C)2004 Novell Inc.
  9. //
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System;
  31. using System.Collections;
  32. using System.IO;
  33. using System.Text;
  34. using System.Xml;
  35. using System.Xml.Schema;
  36. #if NET_2_0
  37. using XmlTextReaderImpl = Mono.Xml2.XmlTextReader;
  38. #else
  39. using XmlTextReaderImpl = System.Xml.XmlTextReader;
  40. #endif
  41. namespace Mono.Xml
  42. {
  43. #if NET_2_0
  44. internal class DTDValidatingReader : XmlReader, IXmlLineInfo, IHasXmlParserContext, IHasXmlSchemaInfo, IXmlNamespaceResolver
  45. #else
  46. internal class DTDValidatingReader : XmlReader, IXmlLineInfo, IHasXmlParserContext, IHasXmlSchemaInfo
  47. #endif
  48. {
  49. public DTDValidatingReader (XmlReader reader)
  50. : this (reader, null)
  51. {
  52. }
  53. internal DTDValidatingReader (XmlReader reader,
  54. XmlValidatingReader validatingReader)
  55. {
  56. entityReaderStack = new Stack ();
  57. entityReaderDepthStack = new Stack ();
  58. this.reader = reader;
  59. this.sourceTextReader = reader as XmlTextReader;
  60. elementStack = new Stack ();
  61. automataStack = new Stack ();
  62. attributes = new ArrayList ();
  63. attributeValues = new Hashtable ();
  64. attributeLocalNames = new Hashtable ();
  65. attributeNamespaces = new Hashtable ();
  66. attributePrefixes = new Hashtable ();
  67. nsdecls = new Hashtable ();
  68. this.validatingReader = validatingReader;
  69. valueBuilder = new StringBuilder ();
  70. idList = new ArrayList ();
  71. missingIDReferences = new ArrayList ();
  72. XmlTextReader xtReader = reader as XmlTextReader;
  73. if (xtReader != null) {
  74. resolver = xtReader.Resolver;
  75. }
  76. else
  77. resolver = new XmlUrlResolver ();
  78. }
  79. Stack entityReaderStack;
  80. Stack entityReaderDepthStack;
  81. XmlReader reader;
  82. XmlTextReader sourceTextReader;
  83. XmlTextReader nextEntityReader;
  84. DTDObjectModel dtd;
  85. Stack elementStack;
  86. Stack automataStack;
  87. string currentElement;
  88. string currentAttribute;
  89. string currentTextValue;
  90. string constructingTextValue;
  91. bool shouldResetCurrentTextValue;
  92. bool consumedAttribute;
  93. bool insideContent;
  94. DTDAutomata currentAutomata;
  95. DTDAutomata previousAutomata;
  96. bool isStandalone;
  97. ArrayList attributes;
  98. Hashtable attributeValues;
  99. Hashtable attributeLocalNames;
  100. Hashtable attributeNamespaces;
  101. Hashtable attributePrefixes;
  102. Hashtable nsdecls;
  103. StringBuilder valueBuilder;
  104. ArrayList idList;
  105. ArrayList missingIDReferences;
  106. XmlResolver resolver;
  107. EntityHandling currentEntityHandling;
  108. bool isSignificantWhitespace;
  109. bool isWhitespace;
  110. bool isText;
  111. bool dontResetTextType;
  112. // This field is used to get properties and to raise events.
  113. XmlValidatingReader validatingReader;
  114. public DTDObjectModel DTD {
  115. get { return dtd; }
  116. }
  117. public EntityHandling EntityHandling {
  118. get { return currentEntityHandling; }
  119. set { currentEntityHandling = value; }
  120. }
  121. public override void Close ()
  122. {
  123. reader.Close ();
  124. }
  125. // We had already done attribute validation, so can ignore name.
  126. public override string GetAttribute (int i)
  127. {
  128. if (currentTextValue != null)
  129. throw new IndexOutOfRangeException ("Specified index is out of range: " + i);
  130. if (dtd == null)
  131. return reader.GetAttribute (i);
  132. if (attributes.Count <= i)
  133. throw new IndexOutOfRangeException ("Specified index is out of range: " + i);
  134. string attrName = (string) attributes [i];
  135. return FilterNormalization (attrName, (string) attributeValues [attrName]);
  136. }
  137. public override string GetAttribute (string name)
  138. {
  139. if (currentTextValue != null)
  140. return null;
  141. if (dtd == null)
  142. return reader.GetAttribute (name);
  143. return FilterNormalization (name, (string) attributeValues [name]);
  144. }
  145. public override string GetAttribute (string name, string ns)
  146. {
  147. if (currentTextValue != null)
  148. return null;
  149. if (dtd == null)
  150. return reader.GetAttribute (name, ns);
  151. return reader.GetAttribute ((string) attributeLocalNames [name], ns);
  152. }
  153. #if NET_2_0
  154. IDictionary IXmlNamespaceResolver.GetNamespacesInScope (XmlNamespaceScope scope)
  155. {
  156. IXmlNamespaceResolver res = reader as IXmlNamespaceResolver;
  157. return res != null ? res.GetNamespacesInScope (scope) : new Hashtable ();
  158. }
  159. #endif
  160. bool IXmlLineInfo.HasLineInfo ()
  161. {
  162. IXmlLineInfo ixli = reader as IXmlLineInfo;
  163. if (ixli != null)
  164. return ixli.HasLineInfo ();
  165. else
  166. return false;
  167. }
  168. public override string LookupNamespace (string prefix)
  169. {
  170. if (nsdecls.Count > 0 && nsdecls [prefix] != null)
  171. return (string) nsdecls [prefix];
  172. return reader.LookupNamespace (prefix);
  173. }
  174. #if NET_2_0
  175. string IXmlNamespaceResolver.LookupPrefix (string ns)
  176. {
  177. IXmlNamespaceResolver res = reader as IXmlNamespaceResolver;
  178. return res != null ? res.LookupPrefix (ns) : null;
  179. }
  180. #endif
  181. public override void MoveToAttribute (int i)
  182. {
  183. if (currentTextValue != null)
  184. throw new IndexOutOfRangeException ("The index is out of range.");
  185. if (dtd == null) {
  186. reader.MoveToAttribute (i);
  187. currentAttribute = reader.Name;
  188. consumedAttribute = false;
  189. return;
  190. }
  191. if (currentElement == null)
  192. throw new IndexOutOfRangeException ("The index is out of range.");
  193. if (attributes.Count > i) {
  194. if (reader.AttributeCount > i)
  195. reader.MoveToAttribute (i);
  196. currentAttribute = (string) attributes [i];
  197. consumedAttribute = false;
  198. return;
  199. } else
  200. throw new IndexOutOfRangeException ("The index is out of range.");
  201. }
  202. public override bool MoveToAttribute (string name)
  203. {
  204. if (currentTextValue != null)
  205. return false;
  206. if (dtd == null) {
  207. bool b = reader.MoveToAttribute (name);
  208. if (b) {
  209. currentAttribute = reader.Name;
  210. consumedAttribute = false;
  211. }
  212. return b;
  213. }
  214. if (currentElement == null)
  215. return false;
  216. int idx = attributes.IndexOf (name);
  217. if (idx >= 0) {
  218. currentAttribute = name;
  219. consumedAttribute = false;
  220. return true;
  221. }
  222. return false;
  223. }
  224. public override bool MoveToAttribute (string name, string ns)
  225. {
  226. if (currentTextValue != null)
  227. return false;
  228. if (dtd == null) {
  229. bool b = reader.MoveToAttribute (name, ns);
  230. if (b) {
  231. currentAttribute = reader.Name;
  232. consumedAttribute = false;
  233. }
  234. return b;
  235. }
  236. if (reader.MoveToAttribute (name, ns)) {
  237. currentAttribute = reader.Name;
  238. consumedAttribute = false;
  239. return true;
  240. }
  241. for (int i = 0; i < attributes.Count; i++) {
  242. string iter = (string) attributes [i];
  243. if ((string) attributeLocalNames [iter] == name)
  244. return MoveToAttribute (iter);
  245. }
  246. return false;
  247. }
  248. public override bool MoveToElement ()
  249. {
  250. if (currentTextValue != null)
  251. return false;
  252. bool b = reader.MoveToElement ();
  253. if (!b && !IsDefault)
  254. return false;
  255. currentAttribute = null;
  256. consumedAttribute = false;
  257. return true;
  258. }
  259. public override bool MoveToFirstAttribute ()
  260. {
  261. if (currentTextValue != null)
  262. return false;
  263. if (dtd == null) {
  264. bool b = reader.MoveToFirstAttribute ();
  265. if (b) {
  266. currentAttribute = reader.Name;
  267. consumedAttribute = false;
  268. }
  269. return b;
  270. }
  271. if (attributes.Count == 0)
  272. return false;
  273. currentAttribute = (string) attributes [0];
  274. reader.MoveToAttribute (currentAttribute);
  275. consumedAttribute = false;
  276. return true;
  277. }
  278. public override bool MoveToNextAttribute ()
  279. {
  280. if (currentTextValue != null)
  281. return false;
  282. if (dtd == null) {
  283. bool b = reader.MoveToNextAttribute ();
  284. if (b) {
  285. currentAttribute = reader.Name;
  286. consumedAttribute = false;
  287. }
  288. return b;
  289. }
  290. if (currentAttribute == null)
  291. return MoveToFirstAttribute ();
  292. int idx = attributes.IndexOf (currentAttribute);
  293. if (idx + 1 < attributes.Count) {
  294. currentAttribute = (string) attributes [idx + 1];
  295. reader.MoveToAttribute (currentAttribute);
  296. consumedAttribute = false;
  297. return true;
  298. } else
  299. return false;
  300. }
  301. /*
  302. private void OnValidationEvent (object o, ValidationEventArgs e)
  303. {
  304. this.HandleError (e.Exception, e.Severity);
  305. }
  306. */
  307. public override bool Read ()
  308. {
  309. if (currentTextValue != null)
  310. shouldResetCurrentTextValue = true;
  311. MoveToElement ();
  312. currentElement = null;
  313. currentAttribute = null;
  314. consumedAttribute = false;
  315. attributes.Clear ();
  316. attributeLocalNames.Clear ();
  317. attributeValues.Clear ();
  318. attributeNamespaces.Clear ();
  319. attributePrefixes.Clear ();
  320. nsdecls.Clear ();
  321. isWhitespace = false;
  322. isSignificantWhitespace = false;
  323. isText = false;
  324. dontResetTextType = false;
  325. bool b = ReadContent () || currentTextValue != null;
  326. if (!b && this.missingIDReferences.Count > 0) {
  327. this.HandleError ("Missing ID reference was found: " +
  328. String.Join (",", missingIDReferences.ToArray (typeof (string)) as string []),
  329. XmlSeverityType.Error);
  330. // Don't output the same errors so many times.
  331. this.missingIDReferences.Clear ();
  332. }
  333. if (validatingReader != null)
  334. EntityHandling = validatingReader.EntityHandling;
  335. return b;
  336. }
  337. private bool ReadContent ()
  338. {
  339. if (nextEntityReader != null) {
  340. if (DTD == null || DTD.EntityDecls [reader.Name] == null)
  341. throw NotWFError (String.Format ("Entity '{0}' was not declared.", reader.Name));
  342. entityReaderStack.Push (reader);
  343. entityReaderDepthStack.Push (Depth);
  344. reader = sourceTextReader = nextEntityReader;
  345. nextEntityReader = null;
  346. return ReadContent ();
  347. } else if (reader.EOF && entityReaderStack.Count > 0) {
  348. reader.Close ();
  349. reader = entityReaderStack.Pop () as XmlReader;
  350. entityReaderDepthStack.Pop ();
  351. sourceTextReader = reader as XmlTextReader;
  352. return ReadContent ();
  353. }
  354. bool b = !reader.EOF;
  355. if (shouldResetCurrentTextValue) {
  356. currentTextValue = null;
  357. shouldResetCurrentTextValue = false;
  358. }
  359. else
  360. b = reader.Read ();
  361. if (!insideContent && reader.NodeType == XmlNodeType.Element) {
  362. insideContent = true;
  363. if (dtd == null)
  364. currentAutomata = null;
  365. else
  366. currentAutomata = dtd.RootAutomata;
  367. }
  368. if (!b) {
  369. if (entityReaderStack.Count > 0) {
  370. if (validatingReader.EntityHandling == EntityHandling.ExpandEntities)
  371. return ReadContent ();
  372. else
  373. return true; // EndEntity
  374. }
  375. if (elementStack.Count != 0)
  376. throw new InvalidOperationException ("Unexpected end of XmlReader.");
  377. return false;
  378. }
  379. DTDElementDeclaration elem = null;
  380. switch (reader.NodeType) {
  381. case XmlNodeType.XmlDeclaration:
  382. if (GetAttribute ("standalone") == "yes")
  383. isStandalone = true;
  384. ValidateAttributes (null, false);
  385. break;
  386. case XmlNodeType.DocumentType:
  387. // XmlTextReader xmlTextReader = reader as XmlTextReader;
  388. IHasXmlParserContext ctx = reader as IHasXmlParserContext;
  389. if (ctx != null)
  390. dtd = ctx.ParserContext.Dtd;
  391. if (dtd == null) {
  392. XmlTextReaderImpl xmlTextReader = new XmlTextReaderImpl ("", XmlNodeType.Document, null);
  393. xmlTextReader.XmlResolver = resolver;
  394. xmlTextReader.GenerateDTDObjectModel (reader.Name,
  395. reader ["PUBLIC"], reader ["SYSTEM"], reader.Value);
  396. dtd = xmlTextReader.DTD;
  397. }
  398. // Validity Constraints Check.
  399. if (DTD.Errors.Length > 0)
  400. for (int i = 0; i < DTD.Errors.Length; i++)
  401. HandleError (DTD.Errors [i].Message, XmlSeverityType.Error);
  402. // NData target exists.
  403. foreach (DTDEntityDeclaration ent in dtd.EntityDecls.Values)
  404. if (ent.NotationName != null && dtd.NotationDecls [ent.NotationName] == null)
  405. this.HandleError ("Target notation was not found for NData in entity declaration " + ent.Name + ".",
  406. XmlSeverityType.Error);
  407. // NOTATION exists for attribute default values
  408. foreach (DTDAttListDeclaration attListIter in dtd.AttListDecls.Values)
  409. foreach (DTDAttributeDefinition def in attListIter.Definitions)
  410. if (def.Datatype.TokenizedType == XmlTokenizedType.NOTATION) {
  411. foreach (string notation in def.EnumeratedNotations)
  412. if (dtd.NotationDecls [notation] == null)
  413. this.HandleError ("Target notation was not found for NOTATION typed attribute default " + def.Name + ".",
  414. XmlSeverityType.Error);
  415. }
  416. break;
  417. case XmlNodeType.Element:
  418. if (constructingTextValue != null) {
  419. currentTextValue = constructingTextValue;
  420. constructingTextValue = null;
  421. if (isWhitespace)
  422. ValidateWhitespaceNode ();
  423. return true;
  424. }
  425. elementStack.Push (reader.Name);
  426. // startElementDeriv
  427. // If no schema specification, then skip validation.
  428. if (currentAutomata == null) {
  429. ValidateAttributes (null, false);
  430. if (reader.IsEmptyElement)
  431. goto case XmlNodeType.EndElement;
  432. break;
  433. }
  434. previousAutomata = currentAutomata;
  435. currentAutomata = currentAutomata.TryStartElement (reader.Name);
  436. if (currentAutomata == DTD.Invalid) {
  437. HandleError (String.Format ("Invalid start element found: {0}", reader.Name),
  438. XmlSeverityType.Error);
  439. currentAutomata = previousAutomata;
  440. }
  441. elem = DTD.ElementDecls [reader.Name];
  442. if (elem == null) {
  443. HandleError (String.Format ("Element {0} is not declared.", reader.Name),
  444. XmlSeverityType.Error);
  445. currentAutomata = previousAutomata;
  446. }
  447. currentElement = Name;
  448. automataStack.Push (currentAutomata);
  449. if (elem != null) // i.e. not invalid
  450. currentAutomata = elem.ContentModel.GetAutomata ();
  451. DTDAttListDeclaration attList = dtd.AttListDecls [currentElement];
  452. if (attList != null) {
  453. // check attributes
  454. ValidateAttributes (attList, true);
  455. currentAttribute = null;
  456. } else {
  457. if (reader.HasAttributes) {
  458. HandleError (String.Format (
  459. "Attributes are found on element {0} while it has no attribute definitions.", currentElement),
  460. XmlSeverityType.Error);
  461. }
  462. // SetupValidityIgnorantAttributes ();
  463. ValidateAttributes (null, false);
  464. }
  465. foreach (string attr in attributes)
  466. if (attr == "xmlns" ||
  467. String.CompareOrdinal (attr, 0, "xmlns", 0, 5) == 0)
  468. nsdecls.Add (
  469. attr == "xmlns" ? String.Empty : attributeLocalNames [attr],
  470. attributeValues [attr]);
  471. // If it is empty element then directly check end element.
  472. if (reader.IsEmptyElement)
  473. goto case XmlNodeType.EndElement;
  474. break;
  475. case XmlNodeType.EndElement:
  476. if (constructingTextValue != null) {
  477. currentTextValue = constructingTextValue;
  478. constructingTextValue = null;
  479. return true;
  480. }
  481. elementStack.Pop ();
  482. // endElementDeriv
  483. // If no schema specification, then skip validation.
  484. if (currentAutomata == null)
  485. break;
  486. elem = DTD.ElementDecls [reader.Name];
  487. if (elem == null) {
  488. HandleError (String.Format ("Element {0} is not declared.", reader.Name),
  489. XmlSeverityType.Error);
  490. }
  491. previousAutomata = currentAutomata;
  492. // Don't let currentAutomata
  493. DTDAutomata tmpAutomata = currentAutomata.TryEndElement ();
  494. if (tmpAutomata == DTD.Invalid) {
  495. HandleError (String.Format ("Invalid end element found: {0}", reader.Name),
  496. XmlSeverityType.Error);
  497. currentAutomata = previousAutomata;
  498. }
  499. currentAutomata = automataStack.Pop () as DTDAutomata;
  500. break;
  501. case XmlNodeType.CDATA:
  502. isSignificantWhitespace = isWhitespace = false;
  503. isText = true;
  504. ValidateText ();
  505. if (currentTextValue != null) {
  506. currentTextValue = constructingTextValue;
  507. constructingTextValue = null;
  508. return true;
  509. }
  510. break;
  511. case XmlNodeType.SignificantWhitespace:
  512. if (!isText)
  513. isSignificantWhitespace = true;
  514. isWhitespace = false;
  515. dontResetTextType = true;
  516. goto case XmlNodeType.DocumentFragment;
  517. case XmlNodeType.Text:
  518. isWhitespace = isSignificantWhitespace = false;
  519. isText = true;
  520. goto case XmlNodeType.DocumentFragment;
  521. case XmlNodeType.DocumentFragment:
  522. // it should not happen, but in case if
  523. // XmlReader really returns it, just ignore.
  524. if (reader.NodeType == XmlNodeType.DocumentFragment)
  525. break;
  526. ValidateText ();
  527. if (entityReaderStack.Count > 0 && validatingReader.EntityHandling == EntityHandling.ExpandEntities) {
  528. constructingTextValue += reader.Value;
  529. return ReadContent ();
  530. }
  531. break;
  532. case XmlNodeType.Whitespace:
  533. if (!isText && !isSignificantWhitespace)
  534. isWhitespace = true;
  535. goto case XmlNodeType.DocumentFragment;
  536. case XmlNodeType.EntityReference:
  537. if (validatingReader.EntityHandling == EntityHandling.ExpandEntities) {
  538. ResolveEntity ();
  539. return ReadContent ();
  540. }
  541. break;
  542. }
  543. if (isWhitespace)
  544. ValidateWhitespaceNode ();
  545. currentTextValue = constructingTextValue;
  546. constructingTextValue = null;
  547. MoveToElement ();
  548. return true;
  549. }
  550. private void ValidateText ()
  551. {
  552. if (currentAutomata == null)
  553. return;
  554. DTDElementDeclaration elem = null;
  555. if (elementStack.Count > 0)
  556. elem = dtd.ElementDecls [elementStack.Peek () as string];
  557. // Here element should have been already validated, so
  558. // if no matching declaration is found, simply ignore.
  559. if (elem != null && !elem.IsMixedContent && !elem.IsAny && !isWhitespace) {
  560. HandleError (String.Format ("Current element {0} does not allow character data content.", elementStack.Peek () as string),
  561. XmlSeverityType.Error);
  562. currentAutomata = previousAutomata;
  563. }
  564. }
  565. private void ValidateWhitespaceNode ()
  566. {
  567. // VC Standalone Document Declaration (2.9)
  568. if (this.isStandalone && DTD != null && elementStack.Count > 0) {
  569. DTDElementDeclaration elem = DTD.ElementDecls [elementStack.Peek () as string];
  570. if (elem != null && !elem.IsInternalSubset && !elem.IsMixedContent && !elem.IsAny && !elem.IsEmpty)
  571. HandleError ("In standalone document, whitespace cannot appear in an element whose declaration explicitly contains child content model, not Mixed content.", XmlSeverityType.Error);
  572. }
  573. }
  574. private XmlException NotWFError (string message)
  575. {
  576. return new XmlException (this as IXmlLineInfo, BaseURI, message);
  577. }
  578. private void HandleError (string message, XmlSeverityType severity)
  579. {
  580. if (validatingReader != null &&
  581. validatingReader.ValidationType == ValidationType.None)
  582. return;
  583. IXmlLineInfo info = this as IXmlLineInfo;
  584. bool hasLine = info.HasLineInfo ();
  585. XmlSchemaException ex = new XmlSchemaException (
  586. message,
  587. hasLine ? info.LineNumber : 0,
  588. hasLine ? info.LinePosition : 0,
  589. null,
  590. BaseURI,
  591. null);
  592. HandleError (ex, severity);
  593. }
  594. private void HandleError (XmlSchemaException ex, XmlSeverityType severity)
  595. {
  596. if (validatingReader != null &&
  597. validatingReader.ValidationType == ValidationType.None)
  598. return;
  599. if (validatingReader != null)
  600. this.validatingReader.OnValidationEvent (this,
  601. new ValidationEventArgs (ex, ex.Message, severity));
  602. else if (severity == XmlSeverityType.Error)
  603. throw ex;
  604. }
  605. Stack attributeValueEntityStack = new Stack ();
  606. private void ValidateAttributes (DTDAttListDeclaration decl, bool validate)
  607. {
  608. while (reader.MoveToNextAttribute ()) {
  609. string attrName = reader.Name;
  610. this.currentAttribute = attrName;
  611. attributes.Add (attrName);
  612. attributeLocalNames.Add (attrName, reader.LocalName);
  613. attributeNamespaces.Add (attrName, reader.NamespaceURI);
  614. attributePrefixes.Add (attrName, reader.Prefix);
  615. XmlReader targetReader = reader;
  616. string attrValue = null;
  617. // It always resolves entity references on attributes (documented as such).
  618. // if (currentEntityHandling == EntityHandling.ExpandCharEntities)
  619. // attrValue = reader.Value;
  620. // else
  621. {
  622. while (attributeValueEntityStack.Count >= 0) {
  623. if (!targetReader.ReadAttributeValue ()) {
  624. if (attributeValueEntityStack.Count > 0) {
  625. targetReader = attributeValueEntityStack.Pop () as XmlReader;
  626. continue;
  627. } else
  628. break;
  629. }
  630. switch (targetReader.NodeType) {
  631. case XmlNodeType.EntityReference:
  632. DTDEntityDeclaration edecl = DTD.EntityDecls [targetReader.Name];
  633. if (edecl == null) {
  634. HandleError (String.Format ("Referenced entity {0} is not declared.", targetReader.Name),
  635. XmlSeverityType.Error);
  636. } else {
  637. XmlTextReader etr = new XmlTextReader (edecl.EntityValue, XmlNodeType.Attribute, ParserContext);
  638. attributeValueEntityStack.Push (targetReader);
  639. targetReader = etr;
  640. continue;
  641. }
  642. break;
  643. case XmlNodeType.EndEntity:
  644. break;
  645. default:
  646. if (attrValue != null) {
  647. valueBuilder.Append (attrValue);
  648. attrValue = null;
  649. }
  650. if (valueBuilder.Length != 0)
  651. valueBuilder.Append (targetReader.Value);
  652. else
  653. attrValue = targetReader.Value;
  654. break;
  655. }
  656. }
  657. if (attrValue == null) {
  658. attrValue = valueBuilder.ToString ();
  659. valueBuilder.Length = 0;
  660. }
  661. }
  662. reader.MoveToElement ();
  663. reader.MoveToAttribute (attrName);
  664. attributeValues.Add (attrName, attrValue);
  665. if (!validate)
  666. continue;
  667. // Validation
  668. DTDAttributeDefinition def = decl [reader.Name];
  669. if (def == null) {
  670. HandleError (String.Format ("Attribute {0} is not declared.", reader.Name),
  671. XmlSeverityType.Error);
  672. continue;
  673. }
  674. // check enumeration constraint
  675. if (def.EnumeratedAttributeDeclaration.Count > 0)
  676. if (!def.EnumeratedAttributeDeclaration.Contains (
  677. FilterNormalization (reader.Name, attrValue)))
  678. HandleError (String.Format ("Attribute enumeration constraint error in attribute {0}, value {1}.",
  679. reader.Name, attrValue), XmlSeverityType.Error);
  680. if (def.EnumeratedNotations.Count > 0)
  681. if (!def.EnumeratedNotations.Contains (
  682. FilterNormalization (reader.Name, attrValue)))
  683. HandleError (String.Format ("Attribute notation enumeration constraint error in attribute {0}, value {1}.",
  684. reader.Name, attrValue), XmlSeverityType.Error);
  685. // check type constraint
  686. string normalized = null;
  687. if (def.Datatype != null)
  688. normalized = FilterNormalization (def.Name, attrValue);
  689. else
  690. normalized = attrValue;
  691. DTDEntityDeclaration ent;
  692. // Common process to get list value
  693. string [] list = null;
  694. switch (def.Datatype.TokenizedType) {
  695. case XmlTokenizedType.IDREFS:
  696. case XmlTokenizedType.ENTITIES:
  697. case XmlTokenizedType.NMTOKENS:
  698. try {
  699. list = def.Datatype.ParseValue (normalized, NameTable, null) as string [];
  700. } catch (Exception) {
  701. HandleError ("Attribute value is invalid against its data type.", XmlSeverityType.Error);
  702. list = new string [0];
  703. }
  704. break;
  705. default:
  706. try {
  707. def.Datatype.ParseValue (normalized, NameTable, null);
  708. } catch (Exception ex) {
  709. HandleError (String.Format ("Attribute value is invalid against its data type '{0}'. {1}", def.Datatype, ex.Message), XmlSeverityType.Error);
  710. }
  711. break;
  712. }
  713. switch (def.Datatype.TokenizedType) {
  714. case XmlTokenizedType.ID:
  715. if (this.idList.Contains (normalized)) {
  716. HandleError (String.Format ("Node with ID {0} was already appeared.", attrValue),
  717. XmlSeverityType.Error);
  718. } else {
  719. if (missingIDReferences.Contains (normalized))
  720. missingIDReferences.Remove (normalized);
  721. idList.Add (normalized);
  722. }
  723. break;
  724. case XmlTokenizedType.IDREF:
  725. if (!idList.Contains (normalized))
  726. missingIDReferences.Add (normalized);
  727. break;
  728. case XmlTokenizedType.IDREFS:
  729. for (int i = 0; i < list.Length; i++) {
  730. string idref = list [i];
  731. if (!idList.Contains (idref))
  732. missingIDReferences.Add (idref);
  733. }
  734. break;
  735. case XmlTokenizedType.ENTITY:
  736. ent = dtd.EntityDecls [normalized];
  737. if (ent == null)
  738. HandleError ("Reference to undeclared entity was found in attribute: " + reader.Name + ".", XmlSeverityType.Error);
  739. else if (ent.NotationName == null)
  740. HandleError ("The entity specified by entity type value must be an unparsed entity. The entity definition has no NDATA in attribute: " + reader.Name + ".", XmlSeverityType.Error);
  741. break;
  742. case XmlTokenizedType.ENTITIES:
  743. for (int i = 0; i < list.Length; i++) {
  744. string entref = list [i];
  745. ent = dtd.EntityDecls [FilterNormalization (reader.Name, entref)];
  746. if (ent == null)
  747. HandleError ("Reference to undeclared entity was found in attribute: " + reader.Name + ".", XmlSeverityType.Error);
  748. else if (ent.NotationName == null)
  749. HandleError ("The entity specified by ENTITIES type value must be an unparsed entity. The entity definition has no NDATA in attribute: " + reader.Name + ".", XmlSeverityType.Error);
  750. }
  751. break;
  752. // case XmlTokenizedType.NMTOKEN: nothing to do
  753. // case XmlTokenizedType.NMTOKENS: nothing to do
  754. }
  755. if (isStandalone && !def.IsInternalSubset &&
  756. attrValue != normalized)
  757. HandleError ("In standalone document, attribute value characters must not be checked against external definition.", XmlSeverityType.Error);
  758. if (def.OccurenceType ==
  759. DTDAttributeOccurenceType.Fixed &&
  760. attrValue != def.DefaultValue)
  761. HandleError (String.Format ("Fixed attribute {0} in element {1} has invalid value {2}.",
  762. def.Name, decl.Name, attrValue),
  763. XmlSeverityType.Error);
  764. }
  765. if (validate)
  766. VerifyDeclaredAttributes (decl);
  767. MoveToElement ();
  768. }
  769. private void VerifyDeclaredAttributes (DTDAttListDeclaration decl)
  770. {
  771. // Check if all required attributes exist, and/or
  772. // if there is default values, then add them.
  773. for (int i = 0; i < decl.Definitions.Count; i++) {
  774. DTDAttributeDefinition def = (DTDAttributeDefinition) decl.Definitions [i];
  775. if (attributes.Contains (def.Name))
  776. continue;
  777. if (def.OccurenceType == DTDAttributeOccurenceType.Required) {
  778. HandleError (String.Format ("Required attribute {0} in element {1} not found .",
  779. def.Name, decl.Name),
  780. XmlSeverityType.Error);
  781. continue;
  782. }
  783. else if (def.DefaultValue == null)
  784. continue;
  785. if (this.isStandalone && !def.IsInternalSubset)
  786. HandleError ("In standalone document, external default value definition must not be applied.", XmlSeverityType.Error);
  787. switch (validatingReader.ValidationType) {
  788. case ValidationType.Auto:
  789. if (validatingReader.Schemas.Count == 0)
  790. goto case ValidationType.DTD;
  791. break;
  792. case ValidationType.DTD:
  793. case ValidationType.None:
  794. // Other than them, ignore DTD defaults.
  795. attributes.Add (def.Name);
  796. int colonAt = def.Name.IndexOf (':');
  797. attributeLocalNames.Add (def.Name,
  798. colonAt < 0 ? def.Name :
  799. def.Name.Substring (colonAt + 1));
  800. string prefix = colonAt < 0 ?
  801. String.Empty :
  802. def.Name.Substring (0, colonAt);
  803. attributePrefixes.Add (def.Name, prefix);
  804. attributeNamespaces.Add (def.Name, reader.LookupNamespace (prefix));
  805. attributeValues.Add (def.Name, def.DefaultValue);
  806. break;
  807. }
  808. }
  809. }
  810. public override bool ReadAttributeValue ()
  811. {
  812. if (consumedAttribute)
  813. return false;
  814. if (NodeType == XmlNodeType.Attribute &&
  815. currentEntityHandling == EntityHandling.ExpandEntities) {
  816. consumedAttribute = true;
  817. return true;
  818. }
  819. else if (IsDefault) {
  820. consumedAttribute = true;
  821. return true;
  822. }
  823. else
  824. return reader.ReadAttributeValue ();
  825. }
  826. #if NET_1_0
  827. public override string ReadInnerXml ()
  828. {
  829. // MS.NET 1.0 has a serious bug here. It skips validation.
  830. return reader.ReadInnerXml ();
  831. }
  832. public override string ReadOuterXml ()
  833. {
  834. // MS.NET 1.0 has a serious bug here. It skips validation.
  835. return reader.ReadOuterXml ();
  836. }
  837. #endif
  838. public override string ReadString ()
  839. {
  840. // It seems to be the same as ReadInnerXml().
  841. return base.ReadStringInternal ();
  842. }
  843. public override void ResolveEntity ()
  844. {
  845. if (resolver == null)
  846. return;
  847. // "reader." is required since NodeType must not be entityref by nature.
  848. if (reader.NodeType != XmlNodeType.EntityReference)
  849. throw new InvalidOperationException ("The current node is not an Entity Reference");
  850. DTDEntityDeclaration entity = DTD != null ? DTD.EntityDecls [reader.Name] as DTDEntityDeclaration : null;
  851. XmlNodeType xmlReaderNodeType =
  852. (currentAttribute != null) ? XmlNodeType.Attribute : XmlNodeType.Element;
  853. #if NET_2_0
  854. if (entity == null)
  855. throw NotWFError (String.Format ("Reference to undeclared entity '{0}'.", reader.Name));
  856. #endif
  857. // MS.NET 1.x ignores undeclared entity reference here..
  858. if (entity != null && entity.SystemId != null) {
  859. Uri baseUri = entity.BaseURI == String.Empty ? null : new Uri (entity.BaseURI);
  860. Stream stream = resolver.GetEntity (resolver.ResolveUri (baseUri, entity.SystemId), null, typeof (Stream)) as Stream;
  861. nextEntityReader = new XmlTextReader (stream, xmlReaderNodeType, ParserContext);
  862. } else {
  863. string replacementText =
  864. (entity != null) ? entity.EntityValue : String.Empty;
  865. nextEntityReader = new XmlTextReader (replacementText, xmlReaderNodeType, ParserContext);
  866. }
  867. nextEntityReader.XmlResolver = resolver;
  868. }
  869. public override int AttributeCount {
  870. get {
  871. if (currentTextValue != null)
  872. return 0;
  873. if (dtd == null || !insideContent)
  874. return reader.AttributeCount;
  875. return attributes.Count;
  876. }
  877. }
  878. public override string BaseURI {
  879. get {
  880. return reader.BaseURI;
  881. }
  882. }
  883. public override bool CanResolveEntity {
  884. get { return true; }
  885. }
  886. public override int Depth {
  887. get {
  888. int baseNum = reader.Depth;
  889. if (entityReaderDepthStack.Count > 0) {
  890. baseNum += (int) entityReaderDepthStack.Peek ();
  891. if (NodeType != XmlNodeType.EndEntity)
  892. baseNum++;
  893. }
  894. if (currentTextValue != null && reader.NodeType == XmlNodeType.EndElement)
  895. baseNum++;
  896. return IsDefault ? baseNum + 1 : baseNum;
  897. }
  898. }
  899. public override bool EOF {
  900. get { return reader.EOF && entityReaderStack.Count == 0; }
  901. }
  902. public override bool HasValue {
  903. get {
  904. return IsDefault ? true :
  905. currentTextValue != null ? true :
  906. reader.HasValue; }
  907. }
  908. public override bool IsDefault {
  909. get {
  910. if (currentTextValue != null)
  911. return false;
  912. if (currentAttribute == null)
  913. return false;
  914. return reader.GetAttribute (currentAttribute) == null;
  915. }
  916. }
  917. public override bool IsEmptyElement {
  918. get {
  919. if (currentTextValue != null)
  920. return false;
  921. return reader.IsEmptyElement;
  922. }
  923. }
  924. public override string this [int i] {
  925. get { return GetAttribute (i); }
  926. }
  927. public override string this [string name] {
  928. get { return GetAttribute (name); }
  929. }
  930. public override string this [string name, string ns] {
  931. get { return GetAttribute (name, ns); }
  932. }
  933. public int LineNumber {
  934. get {
  935. IXmlLineInfo info = reader as IXmlLineInfo;
  936. return (info != null) ? info.LineNumber : 0;
  937. }
  938. }
  939. public int LinePosition {
  940. get {
  941. IXmlLineInfo info = reader as IXmlLineInfo;
  942. return (info != null) ? info.LinePosition : 0;
  943. }
  944. }
  945. public override string LocalName {
  946. get {
  947. if (currentTextValue != null || consumedAttribute)
  948. return String.Empty;
  949. if (entityReaderStack.Count > 0 && reader.EOF)
  950. return ((XmlReader) entityReaderStack.Peek ()).LocalName; // name of EndEntity
  951. else if (NodeType == XmlNodeType.Attribute)
  952. return (string) attributeLocalNames [currentAttribute];
  953. else if (IsDefault)
  954. return String.Empty;
  955. else
  956. return reader.LocalName;
  957. }
  958. }
  959. public override string Name {
  960. get {
  961. if (currentTextValue != null || consumedAttribute)
  962. return String.Empty;
  963. if (entityReaderStack.Count > 0 && reader.EOF)
  964. return ((XmlReader) entityReaderStack.Peek ()).Name; // name of EndEntity
  965. else if (NodeType == XmlNodeType.Attribute)
  966. return currentAttribute;
  967. else if (IsDefault)
  968. return String.Empty;
  969. else
  970. return reader.Name;
  971. }
  972. }
  973. public override string NamespaceURI {
  974. get {
  975. if (currentTextValue != null || consumedAttribute)
  976. return String.Empty;
  977. else if (NodeType == XmlNodeType.Attribute)
  978. return (string) attributeNamespaces [currentAttribute];
  979. else if (IsDefault)
  980. return String.Empty;
  981. else if (nsdecls.Count > 0 && nsdecls [Prefix] != null)
  982. return (string) nsdecls [Prefix];
  983. else
  984. return reader.NamespaceURI;
  985. }
  986. }
  987. public override XmlNameTable NameTable {
  988. get { return reader.NameTable; }
  989. }
  990. public override XmlNodeType NodeType {
  991. get {
  992. if (currentTextValue != null)
  993. return isSignificantWhitespace ? XmlNodeType.SignificantWhitespace :
  994. isWhitespace ? XmlNodeType.Whitespace :
  995. XmlNodeType.Text;
  996. if (entityReaderStack.Count > 0 && reader.EOF)
  997. return XmlNodeType.EndEntity;
  998. // If consumedAttribute is true, then entities must be resolved.
  999. return consumedAttribute ? XmlNodeType.Text :
  1000. IsDefault ? XmlNodeType.Attribute :
  1001. reader.NodeType;
  1002. }
  1003. }
  1004. public XmlParserContext ParserContext {
  1005. get { return XmlSchemaUtil.GetParserContext (reader); }
  1006. }
  1007. public override string Prefix {
  1008. get {
  1009. if (currentTextValue != null || consumedAttribute)
  1010. return String.Empty;
  1011. else if (NodeType == XmlNodeType.Attribute)
  1012. return (string) attributePrefixes [currentAttribute];
  1013. else if (IsDefault)
  1014. return String.Empty;
  1015. else
  1016. return reader.Prefix;
  1017. }
  1018. }
  1019. public override char QuoteChar {
  1020. get {
  1021. // If it is not actually on an attribute, then it returns
  1022. // undefined value or '"'.
  1023. return reader.QuoteChar;
  1024. }
  1025. }
  1026. public override ReadState ReadState {
  1027. get {
  1028. if (reader.ReadState == ReadState.EndOfFile && currentTextValue != null)
  1029. return ReadState.Interactive;
  1030. return reader.ReadState;
  1031. }
  1032. }
  1033. public object SchemaType {
  1034. get {
  1035. if (currentElement == null)
  1036. return null;
  1037. DTDAttListDeclaration decl =
  1038. DTD.AttListDecls [currentElement];
  1039. DTDAttributeDefinition def =
  1040. decl != null ? decl [currentAttribute] : null;
  1041. return def != null ? def.Datatype : null;
  1042. }
  1043. }
  1044. char [] whitespaceChars = new char [] {' '};
  1045. private string FilterNormalization (string attrName, string rawValue)
  1046. {
  1047. if (DTD == null || NodeType != XmlNodeType.Attribute ||
  1048. sourceTextReader == null ||
  1049. !sourceTextReader.Normalization)
  1050. return rawValue;
  1051. DTDAttributeDefinition def =
  1052. dtd.AttListDecls [currentElement].Get (attrName);
  1053. valueBuilder.Append (rawValue);
  1054. valueBuilder.Replace ('\r', ' ');
  1055. valueBuilder.Replace ('\n', ' ');
  1056. valueBuilder.Replace ('\t', ' ');
  1057. try {
  1058. if (def.Datatype.TokenizedType == XmlTokenizedType.CDATA)
  1059. return valueBuilder.ToString ();
  1060. for (int i=0; i < valueBuilder.Length; i++) {
  1061. if (valueBuilder [i] != ' ')
  1062. continue;
  1063. while (++i < valueBuilder.Length && valueBuilder [i] == ' ')
  1064. valueBuilder.Remove (i, 1);
  1065. }
  1066. return valueBuilder.ToString ().Trim (whitespaceChars);
  1067. } finally {
  1068. valueBuilder.Length = 0;
  1069. }
  1070. }
  1071. public override string Value {
  1072. get {
  1073. if (currentTextValue != null)
  1074. return currentTextValue;
  1075. // This check also covers value node of default attributes.
  1076. if (IsDefault) {
  1077. DTDAttributeDefinition def =
  1078. dtd.AttListDecls [currentElement] [currentAttribute] as DTDAttributeDefinition;
  1079. return sourceTextReader != null && sourceTextReader.Normalization ?
  1080. def.NormalizedDefaultValue : def.DefaultValue;
  1081. }
  1082. // As to this property, MS.NET seems ignorant of EntityHandling...
  1083. else if (NodeType == XmlNodeType.Attribute)// &&
  1084. return FilterNormalization (Name, (string) attributeValues [currentAttribute]);
  1085. else if (consumedAttribute)
  1086. return FilterNormalization (Name, (string) attributeValues [this.currentAttribute]);
  1087. else
  1088. return FilterNormalization (Name, reader.Value);
  1089. }
  1090. }
  1091. public override string XmlLang {
  1092. get {
  1093. string val = this ["xml:lang"];
  1094. return val != null ? val : reader.XmlLang;
  1095. }
  1096. }
  1097. public XmlResolver XmlResolver {
  1098. set {
  1099. resolver = value;
  1100. }
  1101. }
  1102. public override XmlSpace XmlSpace {
  1103. get {
  1104. string val = this ["xml:space"];
  1105. switch (val) {
  1106. case "preserve":
  1107. return XmlSpace.Preserve;
  1108. case "default":
  1109. return XmlSpace.Default;
  1110. default:
  1111. return reader.XmlSpace;
  1112. }
  1113. }
  1114. }
  1115. }
  1116. }