DTDValidatingReader.cs 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  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 { return XmlSchemaUtil.GetParserContext (reader); }
  825. }
  826. public override string Prefix {
  827. get {
  828. if (currentTextValue != null)
  829. return String.Empty;
  830. if (currentAttribute != null && NodeType != XmlNodeType.Attribute)
  831. return String.Empty;
  832. return IsDefault ? String.Empty : reader.Prefix;
  833. }
  834. }
  835. public override char QuoteChar {
  836. get {
  837. // If it is not actually on an attribute, then it returns
  838. // undefined value or '"'.
  839. return reader.QuoteChar;
  840. }
  841. }
  842. public override ReadState ReadState {
  843. get {
  844. if (reader.ReadState == ReadState.EndOfFile && currentTextValue != null)
  845. return ReadState.Interactive;
  846. return reader.ReadState;
  847. }
  848. }
  849. public object SchemaType {
  850. get {
  851. if (currentElement == null)
  852. return null;
  853. DTDAttributeDefinition def =
  854. DTD.AttListDecls [currentElement] [currentAttribute];
  855. return def.Datatype;
  856. }
  857. }
  858. char [] whitespaceChars = new char [] {' '};
  859. private string FilterNormalization (string attrName, string rawValue)
  860. {
  861. if (DTD != null &&
  862. NodeType == XmlNodeType.Attribute &&
  863. sourceTextReader != null &&
  864. sourceTextReader.Normalization) {
  865. DTDAttributeDefinition def =
  866. dtd.AttListDecls [currentElement].Get (attrName);
  867. valueBuilder.Append (rawValue);
  868. valueBuilder.Replace ('\r', ' ');
  869. valueBuilder.Replace ('\n', ' ');
  870. valueBuilder.Replace ('\t', ' ');
  871. try {
  872. if (def.Datatype.TokenizedType != XmlTokenizedType.CDATA) {
  873. for (int i=0; i < valueBuilder.Length; i++) {
  874. if (valueBuilder [i] == ' ') {
  875. while (++i < valueBuilder.Length && valueBuilder [i] == ' ')
  876. valueBuilder.Remove (i, 1);
  877. }
  878. }
  879. return valueBuilder.ToString ().Trim (whitespaceChars);
  880. }
  881. else
  882. return valueBuilder.ToString ();
  883. } finally {
  884. valueBuilder.Length = 0;
  885. }
  886. }
  887. else
  888. return rawValue;
  889. }
  890. public override string Value {
  891. get {
  892. if (currentTextValue != null)
  893. return currentTextValue;
  894. // This check also covers value node of default attributes.
  895. if (IsDefault) {
  896. DTDAttributeDefinition def =
  897. dtd.AttListDecls [currentElement] [currentAttribute] as DTDAttributeDefinition;
  898. return sourceTextReader != null && sourceTextReader.Normalization ?
  899. def.NormalizedDefaultValue : def.DefaultValue;
  900. }
  901. // As to this property, MS.NET seems ignorant of EntityHandling...
  902. else if (NodeType == XmlNodeType.Attribute)// &&
  903. // currentEntityHandling == EntityHandling.ExpandEntities)
  904. return FilterNormalization (Name, attributeValues [currentAttribute]);
  905. else if (consumedAttribute)
  906. return FilterNormalization (Name, attributeValues [this.currentAttribute]);
  907. else
  908. return FilterNormalization (Name, reader.Value);
  909. }
  910. }
  911. public override string XmlLang {
  912. get {
  913. string val = this ["xml:lang"];
  914. return val != null ? val : reader.XmlLang;
  915. }
  916. }
  917. public XmlResolver XmlResolver {
  918. set {
  919. resolver = value;
  920. }
  921. }
  922. public override XmlSpace XmlSpace {
  923. get {
  924. string val = this ["xml:space"];
  925. switch (val) {
  926. case "preserve":
  927. return XmlSpace.Preserve;
  928. case "default":
  929. return XmlSpace.Default;
  930. default:
  931. return reader.XmlSpace;
  932. }
  933. }
  934. }
  935. }
  936. }