DTDValidatingReader.cs 31 KB

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