DTDValidatingReader.cs 36 KB

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