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. 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. SetupValidityIgnorantAttributes ();
  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);
  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. }
  381. // If it is empty element then directly check end element.
  382. if (reader.IsEmptyElement)
  383. goto case XmlNodeType.EndElement;
  384. break;
  385. case XmlNodeType.EndElement:
  386. if (constructingTextValue != null) {
  387. currentTextValue = constructingTextValue;
  388. constructingTextValue = null;
  389. return true;
  390. }
  391. elementStack.Pop ();
  392. // endElementDeriv
  393. // If no schema specification, then skip validation.
  394. if (currentAutomata == null)
  395. break;
  396. decl = DTD.ElementDecls [reader.Name];
  397. if (decl == null) {
  398. HandleError (String.Format ("Element {0} is not declared.", reader.Name),
  399. XmlSeverityType.Error);
  400. }
  401. previousAutomata = currentAutomata;
  402. // Don't let currentAutomata
  403. DTDAutomata tmpAutomata = currentAutomata.TryEndElement ();
  404. if (tmpAutomata == DTD.Invalid) {
  405. HandleError (String.Format ("Invalid end element found: {0}", reader.Name),
  406. XmlSeverityType.Error);
  407. currentAutomata = previousAutomata;
  408. }
  409. currentAutomata = automataStack.Pop () as DTDAutomata;
  410. break;
  411. case XmlNodeType.CDATA:
  412. if (currentTextValue != null) {
  413. currentTextValue = constructingTextValue;
  414. constructingTextValue = null;
  415. return true;
  416. }
  417. goto case XmlNodeType.Text;
  418. case XmlNodeType.SignificantWhitespace:
  419. if (!isText)
  420. isSignificantWhitespace = true;
  421. dontResetTextType = true;
  422. goto case XmlNodeType.Text;
  423. case XmlNodeType.Text:
  424. isText = true;
  425. if (!dontResetTextType) {
  426. isWhitespace = isSignificantWhitespace = false;
  427. }
  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. currentAutomata = previousAutomata;
  438. }
  439. if (validatingReader.EntityHandling == EntityHandling.ExpandEntities) {
  440. constructingTextValue += reader.Value;
  441. return ReadContent ();
  442. }
  443. break;
  444. case XmlNodeType.Whitespace:
  445. if (nextMaybeSignificantWhitespace) {
  446. currentTextValue = reader.Value;
  447. nextMaybeSignificantWhitespace = false;
  448. goto case XmlNodeType.SignificantWhitespace;
  449. }
  450. if (!isText && !isSignificantWhitespace)
  451. isWhitespace = true;
  452. if (validatingReader.EntityHandling == EntityHandling.ExpandEntities) {
  453. constructingTextValue += reader.Value;
  454. return ReadContent ();
  455. }
  456. break;
  457. case XmlNodeType.EntityReference:
  458. if (validatingReader.EntityHandling == EntityHandling.ExpandEntities) {
  459. ResolveEntity ();
  460. return ReadContent ();
  461. }
  462. break;
  463. }
  464. constructingTextValue = null;
  465. MoveToElement ();
  466. return true;
  467. }
  468. private void SetupValidityIgnorantAttributes ()
  469. {
  470. if (reader.MoveToFirstAttribute ()) {
  471. // If it was invalid, simply add specified attributes.
  472. do {
  473. attributes.Add (reader.Name);
  474. attributeLocalNames.Add (reader.Name, reader.LocalName);
  475. attributeNamespaces.Add (reader.Name, reader.NamespaceURI);
  476. attributeValues.Add (reader.Name, reader.Value);
  477. } while (reader.MoveToNextAttribute ());
  478. reader.MoveToElement ();
  479. }
  480. }
  481. private void HandleError (string message, XmlSeverityType severity)
  482. {
  483. if (validatingReader != null &&
  484. validatingReader.ValidationType == ValidationType.None)
  485. return;
  486. IXmlLineInfo info = this as IXmlLineInfo;
  487. bool hasLine = info.HasLineInfo ();
  488. XmlSchemaException ex = new XmlSchemaException (
  489. message,
  490. hasLine ? info.LineNumber : 0,
  491. hasLine ? info.LinePosition : 0,
  492. null,
  493. BaseURI,
  494. null);
  495. if (validatingReader != null)
  496. this.validatingReader.OnValidationEvent (this,
  497. new ValidationEventArgs (ex, ex.Message, severity));
  498. else
  499. throw ex;
  500. }
  501. Stack attributeValueEntityStack = new Stack ();
  502. private void ValidateAttributes (DTDAttListDeclaration decl)
  503. {
  504. while (reader.MoveToNextAttribute ()) {
  505. string attrName = reader.Name;
  506. this.currentAttribute = attrName;
  507. attributes.Add (attrName);
  508. attributeLocalNames.Add (attrName, reader.LocalName);
  509. attributeNamespaces.Add (attrName, reader.NamespaceURI);
  510. bool hasError = false;
  511. XmlReader targetReader = reader;
  512. while (attributeValueEntityStack.Count >= 0) {
  513. if (!targetReader.ReadAttributeValue ()) {
  514. if (attributeValueEntityStack.Count > 0) {
  515. targetReader = attributeValueEntityStack.Pop () as XmlReader;
  516. continue;
  517. } else
  518. break;
  519. }
  520. switch (targetReader.NodeType) {
  521. case XmlNodeType.EntityReference:
  522. DTDEntityDeclaration edecl = DTD.EntityDecls [targetReader.Name];
  523. if (edecl == null) {
  524. HandleError (String.Format ("Referenced entity {0} is not declared.", targetReader.Name),
  525. XmlSeverityType.Error);
  526. hasError = true;
  527. } else {
  528. XmlTextReader etr = new XmlTextReader (edecl.EntityValue, XmlNodeType.Attribute, ParserContext);
  529. attributeValueEntityStack.Push (targetReader);
  530. targetReader = etr;
  531. continue;
  532. }
  533. break;
  534. case XmlNodeType.EndEntity:
  535. break;
  536. default:
  537. valueBuilder.Append (targetReader.Value);
  538. break;
  539. }
  540. }
  541. reader.MoveToElement ();
  542. reader.MoveToAttribute (attrName);
  543. string attrValue = valueBuilder.ToString ();
  544. valueBuilder.Length = 0;
  545. attributeValues.Add (attrName, attrValue);
  546. DTDAttributeDefinition def = decl [reader.Name];
  547. if (def == null) {
  548. HandleError (String.Format ("Attribute {0} is not declared.", reader.Name),
  549. XmlSeverityType.Error);
  550. } else {
  551. // check enumeration constraint
  552. if (def.EnumeratedAttributeDeclaration.Count > 0)
  553. if (!def.EnumeratedAttributeDeclaration.Contains (
  554. FilterNormalization (reader.Name, attrValue)))
  555. HandleError (String.Format ("Attribute enumeration constraint error in attribute {0}, value {1}.",
  556. reader.Name, attrValue), XmlSeverityType.Error);
  557. if (def.EnumeratedNotations.Count > 0)
  558. if (!def.EnumeratedNotations.Contains (
  559. FilterNormalization (reader.Name, attrValue)))
  560. HandleError (String.Format ("Attribute notation enumeration constraint error in attribute {0}, value {1}.",
  561. reader.Name, attrValue), XmlSeverityType.Error);
  562. // check type constraint
  563. string normalized = null;
  564. if (def.Datatype != null)
  565. normalized = FilterNormalization (def.Name, attrValue);
  566. else
  567. normalized = attrValue;
  568. switch (def.Datatype.TokenizedType) {
  569. case XmlTokenizedType.ID:
  570. if (!XmlChar.IsName (normalized))
  571. HandleError (String.Format ("ID attribute value must match the creation rule Name: {0}", attrValue),
  572. XmlSeverityType.Error);
  573. else if (this.idList.Contains (normalized)) {
  574. HandleError (String.Format ("Node with ID {0} was already appeared.", attrValue),
  575. XmlSeverityType.Error);
  576. } else {
  577. if (missingIDReferences.Contains (normalized))
  578. missingIDReferences.Remove (normalized);
  579. idList.Add (normalized);
  580. }
  581. break;
  582. case XmlTokenizedType.IDREF:
  583. if (!XmlChar.IsName (normalized))
  584. HandleError (String.Format ("IDREF attribute value must match the creation rule Name: {0}", attrValue),
  585. XmlSeverityType.Error);
  586. if (!idList.Contains (normalized))
  587. missingIDReferences.Add (normalized);
  588. break;
  589. case XmlTokenizedType.IDREFS:
  590. string [] idrefs = def.Datatype.ParseValue (normalized, NameTable, null) as string [];
  591. foreach (string idref in idrefs) {
  592. string each = FilterNormalization (def.Name, idref);
  593. if (!XmlChar.IsName (each))
  594. HandleError (String.Format ("Each ID in IDREFS attribute value must match the creation rule Name: {0}", attrValue),
  595. XmlSeverityType.Error);
  596. if (!idList.Contains (each))
  597. missingIDReferences.Add (each);
  598. }
  599. break;
  600. case XmlTokenizedType.ENTITY:
  601. if (dtd.EntityDecls [normalized] == null)
  602. HandleError (String.Format ("Reference to undeclared entity was found in attribute {0}.", reader.Name),
  603. XmlSeverityType.Error);
  604. break;
  605. case XmlTokenizedType.ENTITIES:
  606. string [] entrefs = def.Datatype.ParseValue (normalized, NameTable, null) as string [];
  607. foreach (string entref in entrefs) {
  608. if (dtd.EntityDecls [ FilterNormalization (reader.Name, entref) ] == null)
  609. HandleError (String.Format ("Reference to undeclared entity was found in attribute {0}.", reader.Name),
  610. XmlSeverityType.Error);
  611. }
  612. break;
  613. case XmlTokenizedType.NMTOKEN:
  614. if (!XmlChar.IsNmToken (normalized))
  615. HandleError (String.Format ("NMTOKEN attribute value must match the creation rule NMTOKEN. Name={0}", reader.Name),
  616. XmlSeverityType.Error);
  617. break;
  618. case XmlTokenizedType.NMTOKENS:
  619. string [] tokens = def.Datatype.ParseValue (normalized, NameTable, null) as string [];
  620. foreach (string token in tokens)
  621. if (!XmlChar.IsNmToken (FilterNormalization (def.Name, token)))
  622. HandleError (String.Format ("Name Token in NMTOKENS attribute value must match the creation rule NMTOKEN. Name={0}", reader.Name),
  623. XmlSeverityType.Error);
  624. break;
  625. }
  626. if (isStandalone && !def.IsInternalSubset && attrValue != normalized)
  627. HandleError ("In standalone document, attribute value characters must not be checked against external definition.", XmlSeverityType.Error);
  628. if (def.OccurenceType == DTDAttributeOccurenceType.Fixed &&
  629. attrValue != def.DefaultValue) {
  630. HandleError (String.Format ("Fixed attribute {0} in element {1} has invalid value {2}.",
  631. def.Name, decl.Name, attrValue),
  632. XmlSeverityType.Error);
  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. }
  645. else if (def.DefaultValue != null) {
  646. if (this.isStandalone && !def.IsInternalSubset)
  647. HandleError ("In standalone document, external default value definition must not be applied.", XmlSeverityType.Error);
  648. switch (validatingReader.ValidationType) {
  649. case ValidationType.Auto:
  650. if (validatingReader.Schemas.Count == 0)
  651. goto case ValidationType.DTD;
  652. break;
  653. case ValidationType.DTD:
  654. case ValidationType.None:
  655. // Other than them, ignore DTD defaults.
  656. attributes.Add (def.Name);
  657. int colonAt = def.Name.IndexOf (':');
  658. attributeLocalNames.Add (def.Name, colonAt < 0 ? def.Name : def.Name.Substring (colonAt + 1));
  659. attributeNamespaces.Add (def.Name, colonAt < 0 ? def.Name : def.Name.Substring (0, colonAt));
  660. attributeValues.Add (def.Name, def.DefaultValue);
  661. break;
  662. }
  663. }
  664. }
  665. reader.MoveToElement ();
  666. }
  667. public override bool ReadAttributeValue ()
  668. {
  669. if (consumedAttribute)
  670. return false;
  671. if (NodeType == XmlNodeType.Attribute &&
  672. currentEntityHandling == EntityHandling.ExpandEntities) {
  673. consumedAttribute = true;
  674. return true;
  675. }
  676. else if (IsDefault) {
  677. consumedAttribute = true;
  678. return true;
  679. }
  680. else
  681. return reader.ReadAttributeValue ();
  682. }
  683. #if NET_1_0
  684. public override string ReadInnerXml ()
  685. {
  686. // MS.NET 1.0 has a serious bug here. It skips validation.
  687. return reader.ReadInnerXml ();
  688. }
  689. public override string ReadOuterXml ()
  690. {
  691. // MS.NET 1.0 has a serious bug here. It skips validation.
  692. return reader.ReadOuterXml ();
  693. }
  694. #endif
  695. public override string ReadString ()
  696. {
  697. // It seems to be the same as ReadInnerXml().
  698. return base.ReadStringInternal ();
  699. }
  700. public override void ResolveEntity ()
  701. {
  702. if (resolver == null)
  703. return;
  704. // "reader." is required since NodeType must not be entityref by nature.
  705. if (reader.NodeType != XmlNodeType.EntityReference)
  706. throw new InvalidOperationException ("The current node is not an Entity Reference");
  707. DTDEntityDeclaration entity = DTD != null ? DTD.EntityDecls [reader.Name] as DTDEntityDeclaration : null;
  708. XmlNodeType xmlReaderNodeType =
  709. (currentAttribute != null) ? XmlNodeType.Attribute : XmlNodeType.Element;
  710. // MS.NET seems simply ignoring undeclared entity reference here ;-(
  711. if (entity != null && entity.SystemId != null) {
  712. Uri baseUri = entity.BaseURI == null ? null : new Uri (entity.BaseURI);
  713. Stream stream = resolver.GetEntity (resolver.ResolveUri (baseUri, entity.SystemId), null, typeof (Stream)) as Stream;
  714. nextEntityReader = new XmlTextReader (stream, xmlReaderNodeType, ParserContext);
  715. } else {
  716. string replacementText =
  717. (entity != null) ? entity.EntityValue : String.Empty;
  718. nextEntityReader = new XmlTextReader (replacementText, xmlReaderNodeType, ParserContext);
  719. }
  720. nextEntityReader.XmlResolver = resolver;
  721. nextEntityReader.SkipTextDeclaration ();
  722. }
  723. public override int AttributeCount {
  724. get {
  725. if (currentTextValue != null)
  726. return 0;
  727. if (dtd == null || !insideContent)
  728. return reader.AttributeCount;
  729. return attributes.Count;
  730. }
  731. }
  732. public override string BaseURI {
  733. get {
  734. return reader.BaseURI;
  735. }
  736. }
  737. public override bool CanResolveEntity {
  738. get { return true; }
  739. }
  740. public override int Depth {
  741. get {
  742. int baseNum = reader.Depth;
  743. if (entityReaderDepthStack.Count > 0) {
  744. baseNum += (int) entityReaderDepthStack.Peek ();
  745. if (NodeType != XmlNodeType.EndEntity)
  746. baseNum++;
  747. }
  748. if (currentTextValue != null && reader.NodeType == XmlNodeType.EndElement)
  749. baseNum++;
  750. return IsDefault ? baseNum + 1 : baseNum;
  751. }
  752. }
  753. public override bool EOF {
  754. get { return reader.EOF && entityReaderStack.Count == 0; }
  755. }
  756. public override bool HasValue {
  757. get {
  758. return IsDefault ? true :
  759. currentTextValue != null ? true :
  760. reader.HasValue; }
  761. }
  762. public override bool IsDefault {
  763. get {
  764. if (currentTextValue != null)
  765. return false;
  766. if (currentAttribute == null)
  767. return false;
  768. return reader.GetAttribute (currentAttribute) == null;
  769. }
  770. }
  771. public override bool IsEmptyElement {
  772. get {
  773. if (currentTextValue != null)
  774. return false;
  775. return reader.IsEmptyElement;
  776. }
  777. }
  778. public override string this [int i] {
  779. get { return GetAttribute (i); }
  780. }
  781. public override string this [string name] {
  782. get { return GetAttribute (name); }
  783. }
  784. public override string this [string name, string ns] {
  785. get { return GetAttribute (name, ns); }
  786. }
  787. public int LineNumber {
  788. get {
  789. IXmlLineInfo info = reader as IXmlLineInfo;
  790. return (info != null) ? info.LineNumber : 0;
  791. }
  792. }
  793. public int LinePosition {
  794. get {
  795. IXmlLineInfo info = reader as IXmlLineInfo;
  796. return (info != null) ? info.LinePosition : 0;
  797. }
  798. }
  799. public override string LocalName {
  800. get {
  801. if (currentTextValue != null)
  802. return String.Empty;
  803. return IsDefault ?
  804. consumedAttribute ? String.Empty : currentAttribute :
  805. reader.LocalName;
  806. }
  807. }
  808. public override string Name {
  809. get {
  810. if (currentTextValue != null)
  811. return String.Empty;
  812. return IsDefault ?
  813. consumedAttribute ? String.Empty : currentAttribute :
  814. reader.Name;
  815. }
  816. }
  817. public override string NamespaceURI {
  818. get {
  819. if (currentTextValue != null)
  820. return String.Empty;
  821. return IsDefault ?
  822. consumedAttribute ? String.Empty : String.Empty :
  823. reader.NamespaceURI;
  824. }
  825. }
  826. public override XmlNameTable NameTable {
  827. get { return reader.NameTable; }
  828. }
  829. public override XmlNodeType NodeType {
  830. get {
  831. if (currentTextValue != null)
  832. return isSignificantWhitespace ? XmlNodeType.SignificantWhitespace :
  833. isWhitespace ? XmlNodeType.Whitespace :
  834. XmlNodeType.Text;
  835. if (entityReaderStack.Count > 0 && reader.EOF)
  836. return XmlNodeType.EndEntity;
  837. // If consumedAttribute is true, then entities must be resolved.
  838. return consumedAttribute ? XmlNodeType.Text :
  839. IsDefault ? XmlNodeType.Attribute :
  840. reader.NodeType;
  841. }
  842. }
  843. public XmlParserContext ParserContext {
  844. get { return XmlSchemaUtil.GetParserContext (reader); }
  845. }
  846. public override string Prefix {
  847. get {
  848. if (currentTextValue != null)
  849. return String.Empty;
  850. if (currentAttribute != null && NodeType != XmlNodeType.Attribute)
  851. return String.Empty;
  852. return IsDefault ? String.Empty : reader.Prefix;
  853. }
  854. }
  855. public override char QuoteChar {
  856. get {
  857. // If it is not actually on an attribute, then it returns
  858. // undefined value or '"'.
  859. return reader.QuoteChar;
  860. }
  861. }
  862. public override ReadState ReadState {
  863. get {
  864. if (reader.ReadState == ReadState.EndOfFile && currentTextValue != null)
  865. return ReadState.Interactive;
  866. return reader.ReadState;
  867. }
  868. }
  869. public object SchemaType {
  870. get {
  871. if (currentElement == null)
  872. return null;
  873. DTDAttributeDefinition def =
  874. DTD.AttListDecls [currentElement] [currentAttribute];
  875. return def.Datatype;
  876. }
  877. }
  878. char [] whitespaceChars = new char [] {' '};
  879. private string FilterNormalization (string attrName, string rawValue)
  880. {
  881. if (DTD != null &&
  882. NodeType == XmlNodeType.Attribute &&
  883. sourceTextReader != null &&
  884. sourceTextReader.Normalization) {
  885. DTDAttributeDefinition def =
  886. dtd.AttListDecls [currentElement].Get (attrName);
  887. valueBuilder.Append (rawValue);
  888. valueBuilder.Replace ('\r', ' ');
  889. valueBuilder.Replace ('\n', ' ');
  890. valueBuilder.Replace ('\t', ' ');
  891. try {
  892. if (def.Datatype.TokenizedType != XmlTokenizedType.CDATA) {
  893. for (int i=0; i < valueBuilder.Length; i++) {
  894. if (valueBuilder [i] == ' ') {
  895. while (++i < valueBuilder.Length && valueBuilder [i] == ' ')
  896. valueBuilder.Remove (i, 1);
  897. }
  898. }
  899. return valueBuilder.ToString ().Trim (whitespaceChars);
  900. }
  901. else
  902. return valueBuilder.ToString ();
  903. } finally {
  904. valueBuilder.Length = 0;
  905. }
  906. }
  907. else
  908. return rawValue;
  909. }
  910. public override string Value {
  911. get {
  912. if (currentTextValue != null)
  913. return currentTextValue;
  914. // This check also covers value node of default attributes.
  915. if (IsDefault) {
  916. DTDAttributeDefinition def =
  917. dtd.AttListDecls [currentElement] [currentAttribute] as DTDAttributeDefinition;
  918. return sourceTextReader != null && sourceTextReader.Normalization ?
  919. def.NormalizedDefaultValue : def.DefaultValue;
  920. }
  921. // As to this property, MS.NET seems ignorant of EntityHandling...
  922. else if (NodeType == XmlNodeType.Attribute)// &&
  923. // currentEntityHandling == EntityHandling.ExpandEntities)
  924. return FilterNormalization (Name, attributeValues [currentAttribute]);
  925. else if (consumedAttribute)
  926. return FilterNormalization (Name, attributeValues [this.currentAttribute]);
  927. else
  928. return FilterNormalization (Name, reader.Value);
  929. }
  930. }
  931. public override string XmlLang {
  932. get {
  933. string val = this ["xml:lang"];
  934. return val != null ? val : reader.XmlLang;
  935. }
  936. }
  937. public XmlResolver XmlResolver {
  938. set {
  939. resolver = value;
  940. }
  941. }
  942. public override XmlSpace XmlSpace {
  943. get {
  944. string val = this ["xml:space"];
  945. switch (val) {
  946. case "preserve":
  947. return XmlSpace.Preserve;
  948. case "default":
  949. return XmlSpace.Default;
  950. default:
  951. return reader.XmlSpace;
  952. }
  953. }
  954. }
  955. }
  956. }