DTDValidatingReader.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  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 nextMaybeSignificantWhitespace;
  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. nextMaybeSignificantWhitespace = 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. bool dontResetTextType = false;
  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. // If it is empty element then directly check end element.
  465. if (reader.IsEmptyElement)
  466. goto case XmlNodeType.EndElement;
  467. break;
  468. case XmlNodeType.EndElement:
  469. if (constructingTextValue != null) {
  470. currentTextValue = constructingTextValue;
  471. constructingTextValue = null;
  472. return true;
  473. }
  474. elementStack.Pop ();
  475. // endElementDeriv
  476. // If no schema specification, then skip validation.
  477. if (currentAutomata == null)
  478. break;
  479. elem = DTD.ElementDecls [reader.Name];
  480. if (elem == null) {
  481. HandleError (String.Format ("Element {0} is not declared.", reader.Name),
  482. XmlSeverityType.Error);
  483. }
  484. previousAutomata = currentAutomata;
  485. // Don't let currentAutomata
  486. DTDAutomata tmpAutomata = currentAutomata.TryEndElement ();
  487. if (tmpAutomata == DTD.Invalid) {
  488. HandleError (String.Format ("Invalid end element found: {0}", reader.Name),
  489. XmlSeverityType.Error);
  490. currentAutomata = previousAutomata;
  491. }
  492. currentAutomata = automataStack.Pop () as DTDAutomata;
  493. break;
  494. case XmlNodeType.CDATA:
  495. if (currentTextValue != null) {
  496. currentTextValue = constructingTextValue;
  497. constructingTextValue = null;
  498. return true;
  499. }
  500. goto case XmlNodeType.Text;
  501. case XmlNodeType.SignificantWhitespace:
  502. if (!isText)
  503. isSignificantWhitespace = true;
  504. dontResetTextType = true;
  505. goto case XmlNodeType.Text;
  506. case XmlNodeType.Text:
  507. isText = true;
  508. if (!dontResetTextType) {
  509. isWhitespace = isSignificantWhitespace = false;
  510. }
  511. // If no schema specification, then skip validation.
  512. if (currentAutomata == null)
  513. break;
  514. if (elementStack.Count > 0)
  515. elem = dtd.ElementDecls [elementStack.Peek () as string];
  516. // Here element should have been already validated, so
  517. // if no matching declaration is found, simply ignore.
  518. if (elem != null && !elem.IsMixedContent && !elem.IsAny) {
  519. HandleError (String.Format ("Current element {0} does not allow character data content.", elementStack.Peek () as string),
  520. XmlSeverityType.Error);
  521. currentAutomata = previousAutomata;
  522. }
  523. if (entityReaderStack.Count > 0 && validatingReader.EntityHandling == EntityHandling.ExpandEntities) {
  524. constructingTextValue += reader.Value;
  525. return ReadContent ();
  526. }
  527. break;
  528. case XmlNodeType.Whitespace:
  529. if (nextMaybeSignificantWhitespace) {
  530. currentTextValue = reader.Value;
  531. nextMaybeSignificantWhitespace = false;
  532. goto case XmlNodeType.SignificantWhitespace;
  533. }
  534. if (!isText && !isSignificantWhitespace)
  535. isWhitespace = true;
  536. if (entityReaderStack.Count > 0 && validatingReader.EntityHandling == EntityHandling.ExpandEntities) {
  537. constructingTextValue += reader.Value;
  538. return ReadContent ();
  539. }
  540. ValidateWhitespaceNode ();
  541. break;
  542. case XmlNodeType.EntityReference:
  543. if (validatingReader.EntityHandling == EntityHandling.ExpandEntities) {
  544. ResolveEntity ();
  545. return ReadContent ();
  546. }
  547. break;
  548. }
  549. constructingTextValue = null;
  550. MoveToElement ();
  551. return true;
  552. }
  553. private void ValidateWhitespaceNode ()
  554. {
  555. // VC Standalone Document Declaration (2.9)
  556. if (this.isStandalone && DTD != null && elementStack.Count > 0) {
  557. DTDElementDeclaration elem = DTD.ElementDecls [elementStack.Peek () as string];
  558. if (elem != null && !elem.IsInternalSubset && !elem.IsMixedContent && !elem.IsAny && !elem.IsEmpty)
  559. HandleError ("In standalone document, whitespace cannot appear in an element whose declaration explicitly contains child content model, not Mixed content.", XmlSeverityType.Error);
  560. }
  561. }
  562. private XmlException NotWFError (string message)
  563. {
  564. return new XmlException (this as IXmlLineInfo, BaseURI, message);
  565. }
  566. private void HandleError (string message, XmlSeverityType severity)
  567. {
  568. if (validatingReader != null &&
  569. validatingReader.ValidationType == ValidationType.None)
  570. return;
  571. IXmlLineInfo info = this as IXmlLineInfo;
  572. bool hasLine = info.HasLineInfo ();
  573. XmlSchemaException ex = new XmlSchemaException (
  574. message,
  575. hasLine ? info.LineNumber : 0,
  576. hasLine ? info.LinePosition : 0,
  577. null,
  578. BaseURI,
  579. null);
  580. HandleError (ex, severity);
  581. }
  582. private void HandleError (XmlSchemaException ex, XmlSeverityType severity)
  583. {
  584. if (validatingReader != null &&
  585. validatingReader.ValidationType == ValidationType.None)
  586. return;
  587. if (validatingReader != null)
  588. this.validatingReader.OnValidationEvent (this,
  589. new ValidationEventArgs (ex, ex.Message, severity));
  590. else if (severity == XmlSeverityType.Error)
  591. throw ex;
  592. }
  593. Stack attributeValueEntityStack = new Stack ();
  594. private void ValidateAttributes (DTDAttListDeclaration decl, bool validate)
  595. {
  596. while (reader.MoveToNextAttribute ()) {
  597. string attrName = reader.Name;
  598. this.currentAttribute = attrName;
  599. attributes.Add (attrName);
  600. attributeLocalNames.Add (attrName, reader.LocalName);
  601. attributeNamespaces.Add (attrName, reader.NamespaceURI);
  602. attributePrefixes.Add (attrName, reader.Prefix);
  603. XmlReader targetReader = reader;
  604. string attrValue = null;
  605. if (currentEntityHandling == EntityHandling.ExpandCharEntities)
  606. attrValue = reader.Value;
  607. else {
  608. while (attributeValueEntityStack.Count >= 0) {
  609. if (!targetReader.ReadAttributeValue ()) {
  610. if (attributeValueEntityStack.Count > 0) {
  611. targetReader = attributeValueEntityStack.Pop () as XmlReader;
  612. continue;
  613. } else
  614. break;
  615. }
  616. switch (targetReader.NodeType) {
  617. case XmlNodeType.EntityReference:
  618. DTDEntityDeclaration edecl = DTD.EntityDecls [targetReader.Name];
  619. if (edecl == null) {
  620. HandleError (String.Format ("Referenced entity {0} is not declared.", targetReader.Name),
  621. XmlSeverityType.Error);
  622. } else {
  623. XmlTextReader etr = new XmlTextReader (edecl.EntityValue, XmlNodeType.Attribute, ParserContext);
  624. attributeValueEntityStack.Push (targetReader);
  625. targetReader = etr;
  626. continue;
  627. }
  628. break;
  629. case XmlNodeType.EndEntity:
  630. break;
  631. default:
  632. if (attrValue != null) {
  633. valueBuilder.Append (attrValue);
  634. attrValue = null;
  635. }
  636. if (valueBuilder.Length != 0)
  637. valueBuilder.Append (targetReader.Value);
  638. else
  639. attrValue = targetReader.Value;
  640. break;
  641. }
  642. }
  643. if (attrValue == null) {
  644. attrValue = valueBuilder.ToString ();
  645. valueBuilder.Length = 0;
  646. }
  647. }
  648. reader.MoveToElement ();
  649. reader.MoveToAttribute (attrName);
  650. attributeValues.Add (attrName, attrValue);
  651. if (!validate)
  652. continue;
  653. // Validation
  654. DTDAttributeDefinition def = decl [reader.Name];
  655. if (def == null) {
  656. HandleError (String.Format ("Attribute {0} is not declared.", reader.Name),
  657. XmlSeverityType.Error);
  658. continue;
  659. }
  660. // check enumeration constraint
  661. if (def.EnumeratedAttributeDeclaration.Count > 0)
  662. if (!def.EnumeratedAttributeDeclaration.Contains (
  663. FilterNormalization (reader.Name, attrValue)))
  664. HandleError (String.Format ("Attribute enumeration constraint error in attribute {0}, value {1}.",
  665. reader.Name, attrValue), XmlSeverityType.Error);
  666. if (def.EnumeratedNotations.Count > 0)
  667. if (!def.EnumeratedNotations.Contains (
  668. FilterNormalization (reader.Name, attrValue)))
  669. HandleError (String.Format ("Attribute notation enumeration constraint error in attribute {0}, value {1}.",
  670. reader.Name, attrValue), XmlSeverityType.Error);
  671. // check type constraint
  672. string normalized = null;
  673. if (def.Datatype != null)
  674. normalized = FilterNormalization (def.Name, attrValue);
  675. else
  676. normalized = attrValue;
  677. DTDEntityDeclaration ent;
  678. // Common process to get list value
  679. string [] list = null;
  680. switch (def.Datatype.TokenizedType) {
  681. case XmlTokenizedType.IDREFS:
  682. case XmlTokenizedType.ENTITIES:
  683. case XmlTokenizedType.NMTOKENS:
  684. try {
  685. list = def.Datatype.ParseValue (normalized, NameTable, null) as string [];
  686. } catch (Exception) {
  687. HandleError ("Attribute value is invalid against its data type.", XmlSeverityType.Error);
  688. list = new string [0];
  689. }
  690. break;
  691. default:
  692. try {
  693. def.Datatype.ParseValue (normalized, NameTable, null);
  694. } catch (Exception ex) {
  695. HandleError (String.Format ("Attribute value is invalid against its data type '{0}'. {1}", def.Datatype, ex.Message), XmlSeverityType.Error);
  696. }
  697. break;
  698. }
  699. switch (def.Datatype.TokenizedType) {
  700. case XmlTokenizedType.ID:
  701. if (this.idList.Contains (normalized)) {
  702. HandleError (String.Format ("Node with ID {0} was already appeared.", attrValue),
  703. XmlSeverityType.Error);
  704. } else {
  705. if (missingIDReferences.Contains (normalized))
  706. missingIDReferences.Remove (normalized);
  707. idList.Add (normalized);
  708. }
  709. break;
  710. case XmlTokenizedType.IDREF:
  711. if (!idList.Contains (normalized))
  712. missingIDReferences.Add (normalized);
  713. break;
  714. case XmlTokenizedType.IDREFS:
  715. for (int i = 0; i < list.Length; i++) {
  716. string idref = list [i];
  717. if (!idList.Contains (idref))
  718. missingIDReferences.Add (idref);
  719. }
  720. break;
  721. case XmlTokenizedType.ENTITY:
  722. ent = dtd.EntityDecls [normalized];
  723. if (ent == null)
  724. HandleError ("Reference to undeclared entity was found in attribute: " + reader.Name + ".", XmlSeverityType.Error);
  725. else if (ent.NotationName == null)
  726. 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);
  727. break;
  728. case XmlTokenizedType.ENTITIES:
  729. for (int i = 0; i < list.Length; i++) {
  730. string entref = list [i];
  731. ent = dtd.EntityDecls [FilterNormalization (reader.Name, entref)];
  732. if (ent == null)
  733. HandleError ("Reference to undeclared entity was found in attribute: " + reader.Name + ".", XmlSeverityType.Error);
  734. else if (ent.NotationName == null)
  735. 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);
  736. }
  737. break;
  738. // case XmlTokenizedType.NMTOKEN: nothing to do
  739. // case XmlTokenizedType.NMTOKENS: nothing to do
  740. }
  741. if (isStandalone && !def.IsInternalSubset &&
  742. attrValue != normalized)
  743. HandleError ("In standalone document, attribute value characters must not be checked against external definition.", XmlSeverityType.Error);
  744. if (def.OccurenceType ==
  745. DTDAttributeOccurenceType.Fixed &&
  746. attrValue != def.DefaultValue)
  747. HandleError (String.Format ("Fixed attribute {0} in element {1} has invalid value {2}.",
  748. def.Name, decl.Name, attrValue),
  749. XmlSeverityType.Error);
  750. }
  751. if (validate)
  752. VerifyDeclaredAttributes (decl);
  753. MoveToElement ();
  754. }
  755. private void VerifyDeclaredAttributes (DTDAttListDeclaration decl)
  756. {
  757. // Check if all required attributes exist, and/or
  758. // if there is default values, then add them.
  759. for (int i = 0; i < decl.Definitions.Count; i++) {
  760. DTDAttributeDefinition def = (DTDAttributeDefinition) decl.Definitions [i];
  761. if (attributes.Contains (def.Name))
  762. continue;
  763. if (def.OccurenceType == DTDAttributeOccurenceType.Required) {
  764. HandleError (String.Format ("Required attribute {0} in element {1} not found .",
  765. def.Name, decl.Name),
  766. XmlSeverityType.Error);
  767. continue;
  768. }
  769. else if (def.DefaultValue == null)
  770. continue;
  771. if (this.isStandalone && !def.IsInternalSubset)
  772. HandleError ("In standalone document, external default value definition must not be applied.", XmlSeverityType.Error);
  773. switch (validatingReader.ValidationType) {
  774. case ValidationType.Auto:
  775. if (validatingReader.Schemas.Count == 0)
  776. goto case ValidationType.DTD;
  777. break;
  778. case ValidationType.DTD:
  779. case ValidationType.None:
  780. // Other than them, ignore DTD defaults.
  781. attributes.Add (def.Name);
  782. int colonAt = def.Name.IndexOf (':');
  783. attributeLocalNames.Add (def.Name,
  784. colonAt < 0 ? def.Name :
  785. def.Name.Substring (colonAt + 1));
  786. string prefix = colonAt < 0 ?
  787. String.Empty :
  788. def.Name.Substring (0, colonAt);
  789. attributePrefixes.Add (def.Name, prefix);
  790. attributeNamespaces.Add (def.Name, reader.LookupNamespace (prefix));
  791. attributeValues.Add (def.Name, def.DefaultValue);
  792. break;
  793. }
  794. }
  795. }
  796. public override bool ReadAttributeValue ()
  797. {
  798. if (consumedAttribute)
  799. return false;
  800. if (NodeType == XmlNodeType.Attribute &&
  801. currentEntityHandling == EntityHandling.ExpandEntities) {
  802. consumedAttribute = true;
  803. return true;
  804. }
  805. else if (IsDefault) {
  806. consumedAttribute = true;
  807. return true;
  808. }
  809. else
  810. return reader.ReadAttributeValue ();
  811. }
  812. #if NET_1_0
  813. public override string ReadInnerXml ()
  814. {
  815. // MS.NET 1.0 has a serious bug here. It skips validation.
  816. return reader.ReadInnerXml ();
  817. }
  818. public override string ReadOuterXml ()
  819. {
  820. // MS.NET 1.0 has a serious bug here. It skips validation.
  821. return reader.ReadOuterXml ();
  822. }
  823. #endif
  824. public override string ReadString ()
  825. {
  826. // It seems to be the same as ReadInnerXml().
  827. return base.ReadStringInternal ();
  828. }
  829. public override void ResolveEntity ()
  830. {
  831. if (resolver == null)
  832. return;
  833. // "reader." is required since NodeType must not be entityref by nature.
  834. if (reader.NodeType != XmlNodeType.EntityReference)
  835. throw new InvalidOperationException ("The current node is not an Entity Reference");
  836. DTDEntityDeclaration entity = DTD != null ? DTD.EntityDecls [reader.Name] as DTDEntityDeclaration : null;
  837. XmlNodeType xmlReaderNodeType =
  838. (currentAttribute != null) ? XmlNodeType.Attribute : XmlNodeType.Element;
  839. #if NET_2_0
  840. if (entity == null)
  841. throw NotWFError (String.Format ("Reference to undeclared entity '{0}'.", reader.Name));
  842. #endif
  843. // MS.NET 1.x ignores undeclared entity reference here..
  844. if (entity != null && entity.SystemId != null) {
  845. Uri baseUri = entity.BaseURI == null ? null : new Uri (entity.BaseURI);
  846. Stream stream = resolver.GetEntity (resolver.ResolveUri (baseUri, entity.SystemId), null, typeof (Stream)) as Stream;
  847. nextEntityReader = new XmlTextReader (stream, xmlReaderNodeType, ParserContext);
  848. } else {
  849. string replacementText =
  850. (entity != null) ? entity.EntityValue : String.Empty;
  851. nextEntityReader = new XmlTextReader (replacementText, xmlReaderNodeType, ParserContext);
  852. }
  853. nextEntityReader.XmlResolver = resolver;
  854. }
  855. public override int AttributeCount {
  856. get {
  857. if (currentTextValue != null)
  858. return 0;
  859. if (dtd == null || !insideContent)
  860. return reader.AttributeCount;
  861. return attributes.Count;
  862. }
  863. }
  864. public override string BaseURI {
  865. get {
  866. return reader.BaseURI;
  867. }
  868. }
  869. public override bool CanResolveEntity {
  870. get { return true; }
  871. }
  872. public override int Depth {
  873. get {
  874. int baseNum = reader.Depth;
  875. if (entityReaderDepthStack.Count > 0) {
  876. baseNum += (int) entityReaderDepthStack.Peek ();
  877. if (NodeType != XmlNodeType.EndEntity)
  878. baseNum++;
  879. }
  880. if (currentTextValue != null && reader.NodeType == XmlNodeType.EndElement)
  881. baseNum++;
  882. return IsDefault ? baseNum + 1 : baseNum;
  883. }
  884. }
  885. public override bool EOF {
  886. get { return reader.EOF && entityReaderStack.Count == 0; }
  887. }
  888. public override bool HasValue {
  889. get {
  890. return IsDefault ? true :
  891. currentTextValue != null ? true :
  892. reader.HasValue; }
  893. }
  894. public override bool IsDefault {
  895. get {
  896. if (currentTextValue != null)
  897. return false;
  898. if (currentAttribute == null)
  899. return false;
  900. return reader.GetAttribute (currentAttribute) == null;
  901. }
  902. }
  903. public override bool IsEmptyElement {
  904. get {
  905. if (currentTextValue != null)
  906. return false;
  907. return reader.IsEmptyElement;
  908. }
  909. }
  910. public override string this [int i] {
  911. get { return GetAttribute (i); }
  912. }
  913. public override string this [string name] {
  914. get { return GetAttribute (name); }
  915. }
  916. public override string this [string name, string ns] {
  917. get { return GetAttribute (name, ns); }
  918. }
  919. public int LineNumber {
  920. get {
  921. IXmlLineInfo info = reader as IXmlLineInfo;
  922. return (info != null) ? info.LineNumber : 0;
  923. }
  924. }
  925. public int LinePosition {
  926. get {
  927. IXmlLineInfo info = reader as IXmlLineInfo;
  928. return (info != null) ? info.LinePosition : 0;
  929. }
  930. }
  931. public override string LocalName {
  932. get {
  933. if (currentTextValue != null || consumedAttribute)
  934. return String.Empty;
  935. if (entityReaderStack.Count > 0 && reader.EOF)
  936. return ((XmlReader) entityReaderStack.Peek ()).LocalName; // name of EndEntity
  937. else if (NodeType == XmlNodeType.Attribute)
  938. return (string) attributeLocalNames [currentAttribute];
  939. else if (IsDefault)
  940. return String.Empty;
  941. else
  942. return reader.LocalName;
  943. }
  944. }
  945. public override string Name {
  946. get {
  947. if (currentTextValue != null || consumedAttribute)
  948. return String.Empty;
  949. if (entityReaderStack.Count > 0 && reader.EOF)
  950. return ((XmlReader) entityReaderStack.Peek ()).Name; // name of EndEntity
  951. else if (NodeType == XmlNodeType.Attribute)
  952. return currentAttribute;
  953. else if (IsDefault)
  954. return String.Empty;
  955. else
  956. return reader.Name;
  957. }
  958. }
  959. public override string NamespaceURI {
  960. get {
  961. if (currentTextValue != null || consumedAttribute)
  962. return String.Empty;
  963. else if (NodeType == XmlNodeType.Attribute)
  964. return (string) attributeNamespaces [currentAttribute];
  965. else if (IsDefault)
  966. return String.Empty;
  967. else
  968. return reader.NamespaceURI;
  969. }
  970. }
  971. public override XmlNameTable NameTable {
  972. get { return reader.NameTable; }
  973. }
  974. public override XmlNodeType NodeType {
  975. get {
  976. if (currentTextValue != null)
  977. return isSignificantWhitespace ? XmlNodeType.SignificantWhitespace :
  978. isWhitespace ? XmlNodeType.Whitespace :
  979. XmlNodeType.Text;
  980. if (entityReaderStack.Count > 0 && reader.EOF)
  981. return XmlNodeType.EndEntity;
  982. // If consumedAttribute is true, then entities must be resolved.
  983. return consumedAttribute ? XmlNodeType.Text :
  984. IsDefault ? XmlNodeType.Attribute :
  985. reader.NodeType;
  986. }
  987. }
  988. public XmlParserContext ParserContext {
  989. get { return XmlSchemaUtil.GetParserContext (reader); }
  990. }
  991. public override string Prefix {
  992. get {
  993. if (currentTextValue != null || consumedAttribute)
  994. return String.Empty;
  995. else if (NodeType == XmlNodeType.Attribute)
  996. return (string) attributePrefixes [currentAttribute];
  997. else if (IsDefault)
  998. return String.Empty;
  999. else
  1000. return reader.Prefix;
  1001. }
  1002. }
  1003. public override char QuoteChar {
  1004. get {
  1005. // If it is not actually on an attribute, then it returns
  1006. // undefined value or '"'.
  1007. return reader.QuoteChar;
  1008. }
  1009. }
  1010. public override ReadState ReadState {
  1011. get {
  1012. if (reader.ReadState == ReadState.EndOfFile && currentTextValue != null)
  1013. return ReadState.Interactive;
  1014. return reader.ReadState;
  1015. }
  1016. }
  1017. public object SchemaType {
  1018. get {
  1019. if (currentElement == null)
  1020. return null;
  1021. DTDAttListDeclaration decl =
  1022. DTD.AttListDecls [currentElement];
  1023. DTDAttributeDefinition def =
  1024. decl != null ? decl [currentAttribute] : null;
  1025. return def != null ? def.Datatype : null;
  1026. }
  1027. }
  1028. char [] whitespaceChars = new char [] {' '};
  1029. private string FilterNormalization (string attrName, string rawValue)
  1030. {
  1031. if (DTD == null || NodeType != XmlNodeType.Attribute ||
  1032. sourceTextReader == null ||
  1033. !sourceTextReader.Normalization)
  1034. return rawValue;
  1035. DTDAttributeDefinition def =
  1036. dtd.AttListDecls [currentElement].Get (attrName);
  1037. valueBuilder.Append (rawValue);
  1038. valueBuilder.Replace ('\r', ' ');
  1039. valueBuilder.Replace ('\n', ' ');
  1040. valueBuilder.Replace ('\t', ' ');
  1041. try {
  1042. if (def.Datatype.TokenizedType == XmlTokenizedType.CDATA)
  1043. return valueBuilder.ToString ();
  1044. for (int i=0; i < valueBuilder.Length; i++) {
  1045. if (valueBuilder [i] != ' ')
  1046. continue;
  1047. while (++i < valueBuilder.Length && valueBuilder [i] == ' ')
  1048. valueBuilder.Remove (i, 1);
  1049. }
  1050. return valueBuilder.ToString ().Trim (whitespaceChars);
  1051. } finally {
  1052. valueBuilder.Length = 0;
  1053. }
  1054. }
  1055. public override string Value {
  1056. get {
  1057. if (currentTextValue != null)
  1058. return currentTextValue;
  1059. // This check also covers value node of default attributes.
  1060. if (IsDefault) {
  1061. DTDAttributeDefinition def =
  1062. dtd.AttListDecls [currentElement] [currentAttribute] as DTDAttributeDefinition;
  1063. return sourceTextReader != null && sourceTextReader.Normalization ?
  1064. def.NormalizedDefaultValue : def.DefaultValue;
  1065. }
  1066. // As to this property, MS.NET seems ignorant of EntityHandling...
  1067. else if (NodeType == XmlNodeType.Attribute)// &&
  1068. return FilterNormalization (Name, (string) attributeValues [currentAttribute]);
  1069. else if (consumedAttribute)
  1070. return FilterNormalization (Name, (string) attributeValues [this.currentAttribute]);
  1071. else
  1072. return FilterNormalization (Name, reader.Value);
  1073. }
  1074. }
  1075. public override string XmlLang {
  1076. get {
  1077. string val = this ["xml:lang"];
  1078. return val != null ? val : reader.XmlLang;
  1079. }
  1080. }
  1081. public XmlResolver XmlResolver {
  1082. set {
  1083. resolver = value;
  1084. }
  1085. }
  1086. public override XmlSpace XmlSpace {
  1087. get {
  1088. string val = this ["xml:space"];
  1089. switch (val) {
  1090. case "preserve":
  1091. return XmlSpace.Preserve;
  1092. case "default":
  1093. return XmlSpace.Default;
  1094. default:
  1095. return reader.XmlSpace;
  1096. }
  1097. }
  1098. }
  1099. }
  1100. }