DTDValidatingReader.cs 31 KB

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