DTDValidatingReader.cs 35 KB

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