DTDValidatingReader.cs 36 KB

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