DTDValidatingReader.cs 31 KB

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