DTDValidatingReader.cs 36 KB

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