DTDValidatingReader.cs 31 KB

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