DTDValidatingReader.cs 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  1. //
  2. // DTDValidatingReader.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto ([email protected])
  6. //
  7. // (C)2003 Atsushi Enomoto
  8. // (C)2004 Novell Inc.
  9. //
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System;
  31. using System.Collections;
  32. using System.IO;
  33. using System.Text;
  34. using System.Xml;
  35. using System.Xml.Schema;
  36. #if NET_2_0
  37. using XmlTextReaderImpl = Mono.Xml2.XmlTextReader;
  38. #else
  39. using XmlTextReaderImpl = System.Xml.XmlTextReader;
  40. #endif
  41. namespace Mono.Xml
  42. {
  43. #if NET_2_0
  44. internal class DTDValidatingReader : XmlReader, IXmlLineInfo, IHasXmlParserContext, IHasXmlSchemaInfo, IXmlNamespaceResolver
  45. #else
  46. internal class DTDValidatingReader : XmlReader, IXmlLineInfo, IHasXmlParserContext, IHasXmlSchemaInfo
  47. #endif
  48. {
  49. public DTDValidatingReader (XmlReader reader)
  50. : this (reader, null)
  51. {
  52. }
  53. internal DTDValidatingReader (XmlReader reader,
  54. XmlValidatingReader validatingReader)
  55. {
  56. entityReaderStack = new Stack ();
  57. entityReaderDepthStack = new Stack ();
  58. this.reader = reader;
  59. this.sourceTextReader = reader as XmlTextReader;
  60. elementStack = new Stack ();
  61. automataStack = new Stack ();
  62. attributes = new ArrayList ();
  63. attributeValues = new Hashtable ();
  64. attributeLocalNames = new Hashtable ();
  65. attributeNamespaces = new Hashtable ();
  66. attributePrefixes = new Hashtable ();
  67. nsdecls = new Hashtable ();
  68. this.validatingReader = validatingReader;
  69. valueBuilder = new StringBuilder ();
  70. idList = new ArrayList ();
  71. missingIDReferences = new ArrayList ();
  72. XmlTextReader xtReader = reader as XmlTextReader;
  73. if (xtReader != null) {
  74. resolver = xtReader.Resolver;
  75. }
  76. else
  77. resolver = new XmlUrlResolver ();
  78. }
  79. Stack entityReaderStack;
  80. Stack entityReaderDepthStack;
  81. XmlReader reader;
  82. XmlTextReader sourceTextReader;
  83. XmlTextReader nextEntityReader;
  84. DTDObjectModel dtd;
  85. Stack elementStack;
  86. Stack automataStack;
  87. string currentElement;
  88. string currentAttribute;
  89. string currentTextValue;
  90. string constructingTextValue;
  91. bool shouldResetCurrentTextValue;
  92. bool consumedAttribute;
  93. bool insideContent;
  94. DTDAutomata currentAutomata;
  95. DTDAutomata previousAutomata;
  96. bool isStandalone;
  97. ArrayList attributes;
  98. Hashtable attributeValues;
  99. Hashtable attributeLocalNames;
  100. Hashtable attributeNamespaces;
  101. Hashtable attributePrefixes;
  102. Hashtable nsdecls;
  103. StringBuilder valueBuilder;
  104. ArrayList idList;
  105. ArrayList missingIDReferences;
  106. XmlResolver resolver;
  107. EntityHandling currentEntityHandling;
  108. bool isSignificantWhitespace;
  109. bool isWhitespace;
  110. bool isText;
  111. bool dontResetTextType;
  112. // This field is used to get properties and to raise events.
  113. XmlValidatingReader validatingReader;
  114. public DTDObjectModel DTD {
  115. get { return dtd; }
  116. }
  117. public EntityHandling EntityHandling {
  118. get { return currentEntityHandling; }
  119. set { currentEntityHandling = value; }
  120. }
  121. public override void Close ()
  122. {
  123. reader.Close ();
  124. }
  125. // We had already done attribute validation, so can ignore name.
  126. public override string GetAttribute (int i)
  127. {
  128. if (currentTextValue != null)
  129. throw new IndexOutOfRangeException ("Specified index is out of range: " + i);
  130. if (dtd == null)
  131. return reader.GetAttribute (i);
  132. if (attributes.Count <= i)
  133. throw new IndexOutOfRangeException ("Specified index is out of range: " + i);
  134. string attrName = (string) attributes [i];
  135. return FilterNormalization (attrName, (string) attributeValues [attrName]);
  136. }
  137. public override string GetAttribute (string name)
  138. {
  139. if (currentTextValue != null)
  140. return null;
  141. if (dtd == null)
  142. return reader.GetAttribute (name);
  143. return FilterNormalization (name, (string) attributeValues [name]);
  144. }
  145. public override string GetAttribute (string name, string ns)
  146. {
  147. if (currentTextValue != null)
  148. return null;
  149. if (dtd == null)
  150. return reader.GetAttribute (name, ns);
  151. return reader.GetAttribute ((string) attributeLocalNames [name], ns);
  152. }
  153. #if NET_2_0
  154. IDictionary IXmlNamespaceResolver.GetNamespacesInScope (XmlNamespaceScope scope)
  155. {
  156. IXmlNamespaceResolver res = reader as IXmlNamespaceResolver;
  157. return res != null ? res.GetNamespacesInScope (scope) : new Hashtable ();
  158. }
  159. #endif
  160. bool IXmlLineInfo.HasLineInfo ()
  161. {
  162. IXmlLineInfo ixli = reader as IXmlLineInfo;
  163. if (ixli != null)
  164. return ixli.HasLineInfo ();
  165. else
  166. return false;
  167. }
  168. public override string LookupNamespace (string prefix)
  169. {
  170. if (nsdecls.Count > 0 && nsdecls [prefix] != null)
  171. return (string) nsdecls [prefix];
  172. return reader.LookupNamespace (prefix);
  173. }
  174. #if NET_2_0
  175. string IXmlNamespaceResolver.LookupPrefix (string ns)
  176. {
  177. IXmlNamespaceResolver res = reader as IXmlNamespaceResolver;
  178. return res != null ? res.LookupPrefix (ns) : null;
  179. }
  180. #endif
  181. public override void MoveToAttribute (int i)
  182. {
  183. if (currentTextValue != null)
  184. throw new IndexOutOfRangeException ("The index is out of range.");
  185. if (dtd == null) {
  186. reader.MoveToAttribute (i);
  187. currentAttribute = reader.Name;
  188. consumedAttribute = false;
  189. return;
  190. }
  191. if (currentElement == null)
  192. throw new IndexOutOfRangeException ("The index is out of range.");
  193. if (attributes.Count > i) {
  194. if (reader.AttributeCount > i)
  195. reader.MoveToAttribute (i);
  196. currentAttribute = (string) attributes [i];
  197. consumedAttribute = false;
  198. return;
  199. } else
  200. throw new IndexOutOfRangeException ("The index is out of range.");
  201. }
  202. public override bool MoveToAttribute (string name)
  203. {
  204. if (currentTextValue != null)
  205. return false;
  206. if (dtd == null) {
  207. bool b = reader.MoveToAttribute (name);
  208. if (b) {
  209. currentAttribute = reader.Name;
  210. consumedAttribute = false;
  211. }
  212. return b;
  213. }
  214. if (currentElement == null)
  215. return false;
  216. int idx = attributes.IndexOf (name);
  217. if (idx >= 0) {
  218. currentAttribute = name;
  219. consumedAttribute = false;
  220. return true;
  221. }
  222. return false;
  223. }
  224. public override bool MoveToAttribute (string name, string ns)
  225. {
  226. if (currentTextValue != null)
  227. return false;
  228. if (dtd == null) {
  229. bool b = reader.MoveToAttribute (name, ns);
  230. if (b) {
  231. currentAttribute = reader.Name;
  232. consumedAttribute = false;
  233. }
  234. return b;
  235. }
  236. if (reader.MoveToAttribute (name, ns)) {
  237. currentAttribute = reader.Name;
  238. consumedAttribute = false;
  239. return true;
  240. }
  241. for (int i = 0; i < attributes.Count; i++) {
  242. string iter = (string) attributes [i];
  243. if ((string) attributeLocalNames [iter] == name)
  244. return MoveToAttribute (iter);
  245. }
  246. return false;
  247. }
  248. public override bool MoveToElement ()
  249. {
  250. if (currentTextValue != null)
  251. return false;
  252. bool b = reader.MoveToElement ();
  253. if (!b && !IsDefault)
  254. return false;
  255. currentAttribute = null;
  256. consumedAttribute = false;
  257. return true;
  258. }
  259. public override bool MoveToFirstAttribute ()
  260. {
  261. if (currentTextValue != null)
  262. return false;
  263. if (dtd == null) {
  264. bool b = reader.MoveToFirstAttribute ();
  265. if (b) {
  266. currentAttribute = reader.Name;
  267. consumedAttribute = false;
  268. }
  269. return b;
  270. }
  271. if (attributes.Count == 0)
  272. return false;
  273. currentAttribute = (string) attributes [0];
  274. reader.MoveToAttribute (currentAttribute);
  275. consumedAttribute = false;
  276. return true;
  277. }
  278. public override bool MoveToNextAttribute ()
  279. {
  280. if (currentTextValue != null)
  281. return false;
  282. if (dtd == null) {
  283. bool b = reader.MoveToNextAttribute ();
  284. if (b) {
  285. currentAttribute = reader.Name;
  286. consumedAttribute = false;
  287. }
  288. return b;
  289. }
  290. if (currentAttribute == null)
  291. return MoveToFirstAttribute ();
  292. int idx = attributes.IndexOf (currentAttribute);
  293. if (idx + 1 < attributes.Count) {
  294. currentAttribute = (string) attributes [idx + 1];
  295. reader.MoveToAttribute (currentAttribute);
  296. consumedAttribute = false;
  297. return true;
  298. } else
  299. return false;
  300. }
  301. /*
  302. private void OnValidationEvent (object o, ValidationEventArgs e)
  303. {
  304. this.HandleError (e.Exception, e.Severity);
  305. }
  306. */
  307. public override bool Read ()
  308. {
  309. if (currentTextValue != null)
  310. shouldResetCurrentTextValue = true;
  311. MoveToElement ();
  312. currentElement = null;
  313. currentAttribute = null;
  314. consumedAttribute = false;
  315. attributes.Clear ();
  316. attributeLocalNames.Clear ();
  317. attributeValues.Clear ();
  318. attributeNamespaces.Clear ();
  319. attributePrefixes.Clear ();
  320. nsdecls.Clear ();
  321. isWhitespace = false;
  322. isSignificantWhitespace = false;
  323. isText = false;
  324. dontResetTextType = false;
  325. bool b = ReadContent () || currentTextValue != null;
  326. if (!b && this.missingIDReferences.Count > 0) {
  327. this.HandleError ("Missing ID reference was found: " +
  328. String.Join (",", missingIDReferences.ToArray (typeof (string)) as string []),
  329. XmlSeverityType.Error);
  330. // Don't output the same errors so many times.
  331. this.missingIDReferences.Clear ();
  332. }
  333. if (validatingReader != null)
  334. EntityHandling = validatingReader.EntityHandling;
  335. return b;
  336. }
  337. private bool ReadContent ()
  338. {
  339. if (nextEntityReader != null) {
  340. if (DTD == null || DTD.EntityDecls [reader.Name] == null)
  341. throw NotWFError (String.Format ("Entity '{0}' was not declared.", reader.Name));
  342. entityReaderStack.Push (reader);
  343. entityReaderDepthStack.Push (Depth);
  344. reader = sourceTextReader = nextEntityReader;
  345. nextEntityReader = null;
  346. return ReadContent ();
  347. } else if (reader.EOF && entityReaderStack.Count > 0) {
  348. reader = entityReaderStack.Pop () as XmlReader;
  349. entityReaderDepthStack.Pop ();
  350. sourceTextReader = reader as XmlTextReader;
  351. return ReadContent ();
  352. }
  353. bool b = !reader.EOF;
  354. if (shouldResetCurrentTextValue) {
  355. currentTextValue = null;
  356. shouldResetCurrentTextValue = false;
  357. }
  358. else
  359. b = reader.Read ();
  360. if (!insideContent && reader.NodeType == XmlNodeType.Element) {
  361. insideContent = true;
  362. if (dtd == null)
  363. currentAutomata = null;
  364. else
  365. currentAutomata = dtd.RootAutomata;
  366. }
  367. if (!b) {
  368. if (entityReaderStack.Count > 0) {
  369. if (validatingReader.EntityHandling == EntityHandling.ExpandEntities)
  370. return ReadContent ();
  371. else
  372. return true; // EndEntity
  373. }
  374. if (elementStack.Count != 0)
  375. throw new InvalidOperationException ("Unexpected end of XmlReader.");
  376. return false;
  377. }
  378. DTDElementDeclaration elem = null;
  379. switch (reader.NodeType) {
  380. case XmlNodeType.XmlDeclaration:
  381. if (GetAttribute ("standalone") == "yes")
  382. isStandalone = true;
  383. ValidateAttributes (null, false);
  384. break;
  385. case XmlNodeType.DocumentType:
  386. // XmlTextReader xmlTextReader = reader as XmlTextReader;
  387. IHasXmlParserContext ctx = reader as IHasXmlParserContext;
  388. if (ctx != null)
  389. dtd = ctx.ParserContext.Dtd;
  390. if (dtd == null) {
  391. XmlTextReaderImpl xmlTextReader = new XmlTextReaderImpl ("", XmlNodeType.Document, null);
  392. xmlTextReader.XmlResolver = resolver;
  393. xmlTextReader.GenerateDTDObjectModel (reader.Name,
  394. reader ["PUBLIC"], reader ["SYSTEM"], reader.Value);
  395. dtd = xmlTextReader.DTD;
  396. }
  397. // Validity Constraints Check.
  398. if (DTD.Errors.Length > 0)
  399. for (int i = 0; i < DTD.Errors.Length; i++)
  400. HandleError (DTD.Errors [i].Message, XmlSeverityType.Error);
  401. // NData target exists.
  402. foreach (DTDEntityDeclaration ent in dtd.EntityDecls.Values)
  403. if (ent.NotationName != null && dtd.NotationDecls [ent.NotationName] == null)
  404. this.HandleError ("Target notation was not found for NData in entity declaration " + ent.Name + ".",
  405. XmlSeverityType.Error);
  406. // NOTATION exists for attribute default values
  407. foreach (DTDAttListDeclaration attListIter in dtd.AttListDecls.Values)
  408. foreach (DTDAttributeDefinition def in attListIter.Definitions)
  409. if (def.Datatype.TokenizedType == XmlTokenizedType.NOTATION) {
  410. foreach (string notation in def.EnumeratedNotations)
  411. if (dtd.NotationDecls [notation] == null)
  412. this.HandleError ("Target notation was not found for NOTATION typed attribute default " + def.Name + ".",
  413. XmlSeverityType.Error);
  414. }
  415. break;
  416. case XmlNodeType.Element:
  417. if (constructingTextValue != null) {
  418. currentTextValue = constructingTextValue;
  419. constructingTextValue = null;
  420. if (isWhitespace)
  421. ValidateWhitespaceNode ();
  422. return true;
  423. }
  424. elementStack.Push (reader.Name);
  425. // startElementDeriv
  426. // If no schema specification, then skip validation.
  427. if (currentAutomata == null) {
  428. ValidateAttributes (null, false);
  429. if (reader.IsEmptyElement)
  430. goto case XmlNodeType.EndElement;
  431. break;
  432. }
  433. previousAutomata = currentAutomata;
  434. currentAutomata = currentAutomata.TryStartElement (reader.Name);
  435. if (currentAutomata == DTD.Invalid) {
  436. HandleError (String.Format ("Invalid start element found: {0}", reader.Name),
  437. XmlSeverityType.Error);
  438. currentAutomata = previousAutomata;
  439. }
  440. elem = DTD.ElementDecls [reader.Name];
  441. if (elem == null) {
  442. HandleError (String.Format ("Element {0} is not declared.", reader.Name),
  443. XmlSeverityType.Error);
  444. currentAutomata = previousAutomata;
  445. }
  446. currentElement = Name;
  447. automataStack.Push (currentAutomata);
  448. if (elem != null) // i.e. not invalid
  449. currentAutomata = elem.ContentModel.GetAutomata ();
  450. DTDAttListDeclaration attList = dtd.AttListDecls [currentElement];
  451. if (attList != null) {
  452. // check attributes
  453. ValidateAttributes (attList, true);
  454. currentAttribute = null;
  455. } else {
  456. if (reader.HasAttributes) {
  457. HandleError (String.Format (
  458. "Attributes are found on element {0} while it has no attribute definitions.", currentElement),
  459. XmlSeverityType.Error);
  460. }
  461. // SetupValidityIgnorantAttributes ();
  462. ValidateAttributes (null, false);
  463. }
  464. foreach (string attr in attributes)
  465. if (attr == "xmlns" ||
  466. String.CompareOrdinal (attr, 0, "xmlns", 0, 5) == 0)
  467. nsdecls.Add (
  468. attr == "xmlns" ? String.Empty : attributePrefixes [attr],
  469. attributeValues [attr]);
  470. // If it is empty element then directly check end element.
  471. if (reader.IsEmptyElement)
  472. goto case XmlNodeType.EndElement;
  473. break;
  474. case XmlNodeType.EndElement:
  475. if (constructingTextValue != null) {
  476. currentTextValue = constructingTextValue;
  477. constructingTextValue = null;
  478. return true;
  479. }
  480. elementStack.Pop ();
  481. // endElementDeriv
  482. // If no schema specification, then skip validation.
  483. if (currentAutomata == null)
  484. break;
  485. elem = DTD.ElementDecls [reader.Name];
  486. if (elem == null) {
  487. HandleError (String.Format ("Element {0} is not declared.", reader.Name),
  488. XmlSeverityType.Error);
  489. }
  490. previousAutomata = currentAutomata;
  491. // Don't let currentAutomata
  492. DTDAutomata tmpAutomata = currentAutomata.TryEndElement ();
  493. if (tmpAutomata == DTD.Invalid) {
  494. HandleError (String.Format ("Invalid end element found: {0}", reader.Name),
  495. XmlSeverityType.Error);
  496. currentAutomata = previousAutomata;
  497. }
  498. currentAutomata = automataStack.Pop () as DTDAutomata;
  499. break;
  500. case XmlNodeType.CDATA:
  501. if (currentTextValue != null) {
  502. currentTextValue = constructingTextValue;
  503. constructingTextValue = null;
  504. return true;
  505. }
  506. break;
  507. case XmlNodeType.SignificantWhitespace:
  508. if (!isText)
  509. isSignificantWhitespace = true;
  510. dontResetTextType = true;
  511. goto case XmlNodeType.Text;
  512. case XmlNodeType.Text:
  513. isText = true;
  514. if (!dontResetTextType) {
  515. isWhitespace = isSignificantWhitespace = false;
  516. }
  517. // If no schema specification, then skip validation.
  518. if (currentAutomata == null)
  519. break;
  520. if (elementStack.Count > 0)
  521. elem = dtd.ElementDecls [elementStack.Peek () as string];
  522. // Here element should have been already validated, so
  523. // if no matching declaration is found, simply ignore.
  524. if (elem != null && !elem.IsMixedContent && !elem.IsAny) {
  525. HandleError (String.Format ("Current element {0} does not allow character data content.", elementStack.Peek () as string),
  526. XmlSeverityType.Error);
  527. currentAutomata = previousAutomata;
  528. }
  529. if (entityReaderStack.Count > 0 && validatingReader.EntityHandling == EntityHandling.ExpandEntities) {
  530. constructingTextValue += reader.Value;
  531. return ReadContent ();
  532. }
  533. break;
  534. case XmlNodeType.Whitespace:
  535. if (!isText && !isSignificantWhitespace)
  536. isWhitespace = true;
  537. goto case XmlNodeType.Text;
  538. case XmlNodeType.EntityReference:
  539. if (validatingReader.EntityHandling == EntityHandling.ExpandEntities) {
  540. ResolveEntity ();
  541. return ReadContent ();
  542. }
  543. break;
  544. }
  545. if (isWhitespace)
  546. ValidateWhitespaceNode ();
  547. currentTextValue = constructingTextValue;
  548. constructingTextValue = null;
  549. MoveToElement ();
  550. return true;
  551. }
  552. private void ValidateWhitespaceNode ()
  553. {
  554. // VC Standalone Document Declaration (2.9)
  555. if (this.isStandalone && DTD != null && elementStack.Count > 0) {
  556. DTDElementDeclaration elem = DTD.ElementDecls [elementStack.Peek () as string];
  557. if (elem != null && !elem.IsInternalSubset && !elem.IsMixedContent && !elem.IsAny && !elem.IsEmpty)
  558. HandleError ("In standalone document, whitespace cannot appear in an element whose declaration explicitly contains child content model, not Mixed content.", XmlSeverityType.Error);
  559. }
  560. }
  561. private XmlException NotWFError (string message)
  562. {
  563. return new XmlException (this as IXmlLineInfo, BaseURI, message);
  564. }
  565. private void HandleError (string message, XmlSeverityType severity)
  566. {
  567. if (validatingReader != null &&
  568. validatingReader.ValidationType == ValidationType.None)
  569. return;
  570. IXmlLineInfo info = this as IXmlLineInfo;
  571. bool hasLine = info.HasLineInfo ();
  572. XmlSchemaException ex = new XmlSchemaException (
  573. message,
  574. hasLine ? info.LineNumber : 0,
  575. hasLine ? info.LinePosition : 0,
  576. null,
  577. BaseURI,
  578. null);
  579. HandleError (ex, severity);
  580. }
  581. private void HandleError (XmlSchemaException ex, XmlSeverityType severity)
  582. {
  583. if (validatingReader != null &&
  584. validatingReader.ValidationType == ValidationType.None)
  585. return;
  586. if (validatingReader != null)
  587. this.validatingReader.OnValidationEvent (this,
  588. new ValidationEventArgs (ex, ex.Message, severity));
  589. else if (severity == XmlSeverityType.Error)
  590. throw ex;
  591. }
  592. Stack attributeValueEntityStack = new Stack ();
  593. private void ValidateAttributes (DTDAttListDeclaration decl, bool validate)
  594. {
  595. while (reader.MoveToNextAttribute ()) {
  596. string attrName = reader.Name;
  597. this.currentAttribute = attrName;
  598. attributes.Add (attrName);
  599. attributeLocalNames.Add (attrName, reader.LocalName);
  600. attributeNamespaces.Add (attrName, reader.NamespaceURI);
  601. attributePrefixes.Add (attrName, reader.Prefix);
  602. XmlReader targetReader = reader;
  603. string attrValue = null;
  604. // It always resolves entity references on attributes (documented as such).
  605. // if (currentEntityHandling == EntityHandling.ExpandCharEntities)
  606. // attrValue = reader.Value;
  607. // else
  608. {
  609. while (attributeValueEntityStack.Count >= 0) {
  610. if (!targetReader.ReadAttributeValue ()) {
  611. if (attributeValueEntityStack.Count > 0) {
  612. targetReader = attributeValueEntityStack.Pop () as XmlReader;
  613. continue;
  614. } else
  615. break;
  616. }
  617. switch (targetReader.NodeType) {
  618. case XmlNodeType.EntityReference:
  619. DTDEntityDeclaration edecl = DTD.EntityDecls [targetReader.Name];
  620. if (edecl == null) {
  621. HandleError (String.Format ("Referenced entity {0} is not declared.", targetReader.Name),
  622. XmlSeverityType.Error);
  623. } else {
  624. XmlTextReader etr = new XmlTextReader (edecl.EntityValue, XmlNodeType.Attribute, ParserContext);
  625. attributeValueEntityStack.Push (targetReader);
  626. targetReader = etr;
  627. continue;
  628. }
  629. break;
  630. case XmlNodeType.EndEntity:
  631. break;
  632. default:
  633. if (attrValue != null) {
  634. valueBuilder.Append (attrValue);
  635. attrValue = null;
  636. }
  637. if (valueBuilder.Length != 0)
  638. valueBuilder.Append (targetReader.Value);
  639. else
  640. attrValue = targetReader.Value;
  641. break;
  642. }
  643. }
  644. if (attrValue == null) {
  645. attrValue = valueBuilder.ToString ();
  646. valueBuilder.Length = 0;
  647. }
  648. }
  649. reader.MoveToElement ();
  650. reader.MoveToAttribute (attrName);
  651. attributeValues.Add (attrName, attrValue);
  652. if (!validate)
  653. continue;
  654. // Validation
  655. DTDAttributeDefinition def = decl [reader.Name];
  656. if (def == null) {
  657. HandleError (String.Format ("Attribute {0} is not declared.", reader.Name),
  658. XmlSeverityType.Error);
  659. continue;
  660. }
  661. // check enumeration constraint
  662. if (def.EnumeratedAttributeDeclaration.Count > 0)
  663. if (!def.EnumeratedAttributeDeclaration.Contains (
  664. FilterNormalization (reader.Name, attrValue)))
  665. HandleError (String.Format ("Attribute enumeration constraint error in attribute {0}, value {1}.",
  666. reader.Name, attrValue), XmlSeverityType.Error);
  667. if (def.EnumeratedNotations.Count > 0)
  668. if (!def.EnumeratedNotations.Contains (
  669. FilterNormalization (reader.Name, attrValue)))
  670. HandleError (String.Format ("Attribute notation enumeration constraint error in attribute {0}, value {1}.",
  671. reader.Name, attrValue), XmlSeverityType.Error);
  672. // check type constraint
  673. string normalized = null;
  674. if (def.Datatype != null)
  675. normalized = FilterNormalization (def.Name, attrValue);
  676. else
  677. normalized = attrValue;
  678. DTDEntityDeclaration ent;
  679. // Common process to get list value
  680. string [] list = null;
  681. switch (def.Datatype.TokenizedType) {
  682. case XmlTokenizedType.IDREFS:
  683. case XmlTokenizedType.ENTITIES:
  684. case XmlTokenizedType.NMTOKENS:
  685. try {
  686. list = def.Datatype.ParseValue (normalized, NameTable, null) as string [];
  687. } catch (Exception) {
  688. HandleError ("Attribute value is invalid against its data type.", XmlSeverityType.Error);
  689. list = new string [0];
  690. }
  691. break;
  692. default:
  693. try {
  694. def.Datatype.ParseValue (normalized, NameTable, null);
  695. } catch (Exception ex) {
  696. HandleError (String.Format ("Attribute value is invalid against its data type '{0}'. {1}", def.Datatype, ex.Message), XmlSeverityType.Error);
  697. }
  698. break;
  699. }
  700. switch (def.Datatype.TokenizedType) {
  701. case XmlTokenizedType.ID:
  702. if (this.idList.Contains (normalized)) {
  703. HandleError (String.Format ("Node with ID {0} was already appeared.", attrValue),
  704. XmlSeverityType.Error);
  705. } else {
  706. if (missingIDReferences.Contains (normalized))
  707. missingIDReferences.Remove (normalized);
  708. idList.Add (normalized);
  709. }
  710. break;
  711. case XmlTokenizedType.IDREF:
  712. if (!idList.Contains (normalized))
  713. missingIDReferences.Add (normalized);
  714. break;
  715. case XmlTokenizedType.IDREFS:
  716. for (int i = 0; i < list.Length; i++) {
  717. string idref = list [i];
  718. if (!idList.Contains (idref))
  719. missingIDReferences.Add (idref);
  720. }
  721. break;
  722. case XmlTokenizedType.ENTITY:
  723. ent = dtd.EntityDecls [normalized];
  724. if (ent == null)
  725. HandleError ("Reference to undeclared entity was found in attribute: " + reader.Name + ".", XmlSeverityType.Error);
  726. else if (ent.NotationName == null)
  727. HandleError ("The entity specified by entity type value must be an unparsed entity. The entity definition has no NDATA in attribute: " + reader.Name + ".", XmlSeverityType.Error);
  728. break;
  729. case XmlTokenizedType.ENTITIES:
  730. for (int i = 0; i < list.Length; i++) {
  731. string entref = list [i];
  732. ent = dtd.EntityDecls [FilterNormalization (reader.Name, entref)];
  733. if (ent == null)
  734. HandleError ("Reference to undeclared entity was found in attribute: " + reader.Name + ".", XmlSeverityType.Error);
  735. else if (ent.NotationName == null)
  736. HandleError ("The entity specified by ENTITIES type value must be an unparsed entity. The entity definition has no NDATA in attribute: " + reader.Name + ".", XmlSeverityType.Error);
  737. }
  738. break;
  739. // case XmlTokenizedType.NMTOKEN: nothing to do
  740. // case XmlTokenizedType.NMTOKENS: nothing to do
  741. }
  742. if (isStandalone && !def.IsInternalSubset &&
  743. attrValue != normalized)
  744. HandleError ("In standalone document, attribute value characters must not be checked against external definition.", XmlSeverityType.Error);
  745. if (def.OccurenceType ==
  746. DTDAttributeOccurenceType.Fixed &&
  747. attrValue != def.DefaultValue)
  748. HandleError (String.Format ("Fixed attribute {0} in element {1} has invalid value {2}.",
  749. def.Name, decl.Name, attrValue),
  750. XmlSeverityType.Error);
  751. }
  752. if (validate)
  753. VerifyDeclaredAttributes (decl);
  754. MoveToElement ();
  755. }
  756. private void VerifyDeclaredAttributes (DTDAttListDeclaration decl)
  757. {
  758. // Check if all required attributes exist, and/or
  759. // if there is default values, then add them.
  760. for (int i = 0; i < decl.Definitions.Count; i++) {
  761. DTDAttributeDefinition def = (DTDAttributeDefinition) decl.Definitions [i];
  762. if (attributes.Contains (def.Name))
  763. continue;
  764. if (def.OccurenceType == DTDAttributeOccurenceType.Required) {
  765. HandleError (String.Format ("Required attribute {0} in element {1} not found .",
  766. def.Name, decl.Name),
  767. XmlSeverityType.Error);
  768. continue;
  769. }
  770. else if (def.DefaultValue == null)
  771. continue;
  772. if (this.isStandalone && !def.IsInternalSubset)
  773. HandleError ("In standalone document, external default value definition must not be applied.", XmlSeverityType.Error);
  774. switch (validatingReader.ValidationType) {
  775. case ValidationType.Auto:
  776. if (validatingReader.Schemas.Count == 0)
  777. goto case ValidationType.DTD;
  778. break;
  779. case ValidationType.DTD:
  780. case ValidationType.None:
  781. // Other than them, ignore DTD defaults.
  782. attributes.Add (def.Name);
  783. int colonAt = def.Name.IndexOf (':');
  784. attributeLocalNames.Add (def.Name,
  785. colonAt < 0 ? def.Name :
  786. def.Name.Substring (colonAt + 1));
  787. string prefix = colonAt < 0 ?
  788. String.Empty :
  789. def.Name.Substring (0, colonAt);
  790. attributePrefixes.Add (def.Name, prefix);
  791. attributeNamespaces.Add (def.Name, reader.LookupNamespace (prefix));
  792. attributeValues.Add (def.Name, def.DefaultValue);
  793. break;
  794. }
  795. }
  796. }
  797. public override bool ReadAttributeValue ()
  798. {
  799. if (consumedAttribute)
  800. return false;
  801. if (NodeType == XmlNodeType.Attribute &&
  802. currentEntityHandling == EntityHandling.ExpandEntities) {
  803. consumedAttribute = true;
  804. return true;
  805. }
  806. else if (IsDefault) {
  807. consumedAttribute = true;
  808. return true;
  809. }
  810. else
  811. return reader.ReadAttributeValue ();
  812. }
  813. #if NET_1_0
  814. public override string ReadInnerXml ()
  815. {
  816. // MS.NET 1.0 has a serious bug here. It skips validation.
  817. return reader.ReadInnerXml ();
  818. }
  819. public override string ReadOuterXml ()
  820. {
  821. // MS.NET 1.0 has a serious bug here. It skips validation.
  822. return reader.ReadOuterXml ();
  823. }
  824. #endif
  825. public override string ReadString ()
  826. {
  827. // It seems to be the same as ReadInnerXml().
  828. return base.ReadStringInternal ();
  829. }
  830. public override void ResolveEntity ()
  831. {
  832. if (resolver == null)
  833. return;
  834. // "reader." is required since NodeType must not be entityref by nature.
  835. if (reader.NodeType != XmlNodeType.EntityReference)
  836. throw new InvalidOperationException ("The current node is not an Entity Reference");
  837. DTDEntityDeclaration entity = DTD != null ? DTD.EntityDecls [reader.Name] as DTDEntityDeclaration : null;
  838. XmlNodeType xmlReaderNodeType =
  839. (currentAttribute != null) ? XmlNodeType.Attribute : XmlNodeType.Element;
  840. #if NET_2_0
  841. if (entity == null)
  842. throw NotWFError (String.Format ("Reference to undeclared entity '{0}'.", reader.Name));
  843. #endif
  844. // MS.NET 1.x ignores undeclared entity reference here..
  845. if (entity != null && entity.SystemId != null) {
  846. Uri baseUri = entity.BaseURI == null ? null : new Uri (entity.BaseURI);
  847. Stream stream = resolver.GetEntity (resolver.ResolveUri (baseUri, entity.SystemId), null, typeof (Stream)) as Stream;
  848. nextEntityReader = new XmlTextReader (stream, xmlReaderNodeType, ParserContext);
  849. } else {
  850. string replacementText =
  851. (entity != null) ? entity.EntityValue : String.Empty;
  852. nextEntityReader = new XmlTextReader (replacementText, xmlReaderNodeType, ParserContext);
  853. }
  854. nextEntityReader.XmlResolver = resolver;
  855. }
  856. public override int AttributeCount {
  857. get {
  858. if (currentTextValue != null)
  859. return 0;
  860. if (dtd == null || !insideContent)
  861. return reader.AttributeCount;
  862. return attributes.Count;
  863. }
  864. }
  865. public override string BaseURI {
  866. get {
  867. return reader.BaseURI;
  868. }
  869. }
  870. public override bool CanResolveEntity {
  871. get { return true; }
  872. }
  873. public override int Depth {
  874. get {
  875. int baseNum = reader.Depth;
  876. if (entityReaderDepthStack.Count > 0) {
  877. baseNum += (int) entityReaderDepthStack.Peek ();
  878. if (NodeType != XmlNodeType.EndEntity)
  879. baseNum++;
  880. }
  881. if (currentTextValue != null && reader.NodeType == XmlNodeType.EndElement)
  882. baseNum++;
  883. return IsDefault ? baseNum + 1 : baseNum;
  884. }
  885. }
  886. public override bool EOF {
  887. get { return reader.EOF && entityReaderStack.Count == 0; }
  888. }
  889. public override bool HasValue {
  890. get {
  891. return IsDefault ? true :
  892. currentTextValue != null ? true :
  893. reader.HasValue; }
  894. }
  895. public override bool IsDefault {
  896. get {
  897. if (currentTextValue != null)
  898. return false;
  899. if (currentAttribute == null)
  900. return false;
  901. return reader.GetAttribute (currentAttribute) == null;
  902. }
  903. }
  904. public override bool IsEmptyElement {
  905. get {
  906. if (currentTextValue != null)
  907. return false;
  908. return reader.IsEmptyElement;
  909. }
  910. }
  911. public override string this [int i] {
  912. get { return GetAttribute (i); }
  913. }
  914. public override string this [string name] {
  915. get { return GetAttribute (name); }
  916. }
  917. public override string this [string name, string ns] {
  918. get { return GetAttribute (name, ns); }
  919. }
  920. public int LineNumber {
  921. get {
  922. IXmlLineInfo info = reader as IXmlLineInfo;
  923. return (info != null) ? info.LineNumber : 0;
  924. }
  925. }
  926. public int LinePosition {
  927. get {
  928. IXmlLineInfo info = reader as IXmlLineInfo;
  929. return (info != null) ? info.LinePosition : 0;
  930. }
  931. }
  932. public override string LocalName {
  933. get {
  934. if (currentTextValue != null || consumedAttribute)
  935. return String.Empty;
  936. if (entityReaderStack.Count > 0 && reader.EOF)
  937. return ((XmlReader) entityReaderStack.Peek ()).LocalName; // name of EndEntity
  938. else if (NodeType == XmlNodeType.Attribute)
  939. return (string) attributeLocalNames [currentAttribute];
  940. else if (IsDefault)
  941. return String.Empty;
  942. else
  943. return reader.LocalName;
  944. }
  945. }
  946. public override string Name {
  947. get {
  948. if (currentTextValue != null || consumedAttribute)
  949. return String.Empty;
  950. if (entityReaderStack.Count > 0 && reader.EOF)
  951. return ((XmlReader) entityReaderStack.Peek ()).Name; // name of EndEntity
  952. else if (NodeType == XmlNodeType.Attribute)
  953. return currentAttribute;
  954. else if (IsDefault)
  955. return String.Empty;
  956. else
  957. return reader.Name;
  958. }
  959. }
  960. public override string NamespaceURI {
  961. get {
  962. if (currentTextValue != null || consumedAttribute)
  963. return String.Empty;
  964. else if (NodeType == XmlNodeType.Attribute)
  965. return (string) attributeNamespaces [currentAttribute];
  966. else if (IsDefault)
  967. return String.Empty;
  968. else if (nsdecls.Count > 0 && nsdecls [Prefix] != null)
  969. return (string) nsdecls [Prefix];
  970. else
  971. return reader.NamespaceURI;
  972. }
  973. }
  974. public override XmlNameTable NameTable {
  975. get { return reader.NameTable; }
  976. }
  977. public override XmlNodeType NodeType {
  978. get {
  979. if (currentTextValue != null)
  980. return isSignificantWhitespace ? XmlNodeType.SignificantWhitespace :
  981. isWhitespace ? XmlNodeType.Whitespace :
  982. XmlNodeType.Text;
  983. if (entityReaderStack.Count > 0 && reader.EOF)
  984. return XmlNodeType.EndEntity;
  985. // If consumedAttribute is true, then entities must be resolved.
  986. return consumedAttribute ? XmlNodeType.Text :
  987. IsDefault ? XmlNodeType.Attribute :
  988. reader.NodeType;
  989. }
  990. }
  991. public XmlParserContext ParserContext {
  992. get { return XmlSchemaUtil.GetParserContext (reader); }
  993. }
  994. public override string Prefix {
  995. get {
  996. if (currentTextValue != null || consumedAttribute)
  997. return String.Empty;
  998. else if (NodeType == XmlNodeType.Attribute)
  999. return (string) attributePrefixes [currentAttribute];
  1000. else if (IsDefault)
  1001. return String.Empty;
  1002. else
  1003. return reader.Prefix;
  1004. }
  1005. }
  1006. public override char QuoteChar {
  1007. get {
  1008. // If it is not actually on an attribute, then it returns
  1009. // undefined value or '"'.
  1010. return reader.QuoteChar;
  1011. }
  1012. }
  1013. public override ReadState ReadState {
  1014. get {
  1015. if (reader.ReadState == ReadState.EndOfFile && currentTextValue != null)
  1016. return ReadState.Interactive;
  1017. return reader.ReadState;
  1018. }
  1019. }
  1020. public object SchemaType {
  1021. get {
  1022. if (currentElement == null)
  1023. return null;
  1024. DTDAttListDeclaration decl =
  1025. DTD.AttListDecls [currentElement];
  1026. DTDAttributeDefinition def =
  1027. decl != null ? decl [currentAttribute] : null;
  1028. return def != null ? def.Datatype : null;
  1029. }
  1030. }
  1031. char [] whitespaceChars = new char [] {' '};
  1032. private string FilterNormalization (string attrName, string rawValue)
  1033. {
  1034. if (DTD == null || NodeType != XmlNodeType.Attribute ||
  1035. sourceTextReader == null ||
  1036. !sourceTextReader.Normalization)
  1037. return rawValue;
  1038. DTDAttributeDefinition def =
  1039. dtd.AttListDecls [currentElement].Get (attrName);
  1040. valueBuilder.Append (rawValue);
  1041. valueBuilder.Replace ('\r', ' ');
  1042. valueBuilder.Replace ('\n', ' ');
  1043. valueBuilder.Replace ('\t', ' ');
  1044. try {
  1045. if (def.Datatype.TokenizedType == XmlTokenizedType.CDATA)
  1046. return valueBuilder.ToString ();
  1047. for (int i=0; i < valueBuilder.Length; i++) {
  1048. if (valueBuilder [i] != ' ')
  1049. continue;
  1050. while (++i < valueBuilder.Length && valueBuilder [i] == ' ')
  1051. valueBuilder.Remove (i, 1);
  1052. }
  1053. return valueBuilder.ToString ().Trim (whitespaceChars);
  1054. } finally {
  1055. valueBuilder.Length = 0;
  1056. }
  1057. }
  1058. public override string Value {
  1059. get {
  1060. if (currentTextValue != null)
  1061. return currentTextValue;
  1062. // This check also covers value node of default attributes.
  1063. if (IsDefault) {
  1064. DTDAttributeDefinition def =
  1065. dtd.AttListDecls [currentElement] [currentAttribute] as DTDAttributeDefinition;
  1066. return sourceTextReader != null && sourceTextReader.Normalization ?
  1067. def.NormalizedDefaultValue : def.DefaultValue;
  1068. }
  1069. // As to this property, MS.NET seems ignorant of EntityHandling...
  1070. else if (NodeType == XmlNodeType.Attribute)// &&
  1071. return FilterNormalization (Name, (string) attributeValues [currentAttribute]);
  1072. else if (consumedAttribute)
  1073. return FilterNormalization (Name, (string) attributeValues [this.currentAttribute]);
  1074. else
  1075. return FilterNormalization (Name, reader.Value);
  1076. }
  1077. }
  1078. public override string XmlLang {
  1079. get {
  1080. string val = this ["xml:lang"];
  1081. return val != null ? val : reader.XmlLang;
  1082. }
  1083. }
  1084. public XmlResolver XmlResolver {
  1085. set {
  1086. resolver = value;
  1087. }
  1088. }
  1089. public override XmlSpace XmlSpace {
  1090. get {
  1091. string val = this ["xml:space"];
  1092. switch (val) {
  1093. case "preserve":
  1094. return XmlSpace.Preserve;
  1095. case "default":
  1096. return XmlSpace.Default;
  1097. default:
  1098. return reader.XmlSpace;
  1099. }
  1100. }
  1101. }
  1102. }
  1103. }