DTDValidatingReader.cs 32 KB

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