DTDValidatingReader.cs 33 KB

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