SmallXmlParser.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. //
  2. // SmallXmlParser.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <atsushi@ximian.com>
  6. //
  7. // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. //
  29. // small xml parser that is mostly compatible with
  30. //
  31. using System;
  32. using System.Collections;
  33. using System.Globalization;
  34. using System.IO;
  35. using System.Text;
  36. namespace Mono.Xml
  37. {
  38. public class SmallXmlParser
  39. {
  40. public interface IContentHandler
  41. {
  42. void OnStartParsing (SmallXmlParser parser);
  43. void OnEndParsing (SmallXmlParser parser);
  44. void OnStartElement (string name, IAttrList attrs);
  45. void OnEndElement (string name);
  46. void OnProcessingInstruction (string name, string text);
  47. void OnChars (string text);
  48. void OnIgnorableWhitespace (string text);
  49. }
  50. public interface IAttrList
  51. {
  52. int Length { get; }
  53. bool IsEmpty { get; }
  54. string GetName (int i);
  55. string GetValue (int i);
  56. string GetValue (string name);
  57. string [] Names { get; }
  58. string [] Values { get; }
  59. }
  60. class AttrListImpl : IAttrList
  61. {
  62. public int Length {
  63. get { return attrNames.Count; }
  64. }
  65. public bool IsEmpty {
  66. get { return attrNames.Count == 0; }
  67. }
  68. public string GetName (int i)
  69. {
  70. return (string) attrNames [i];
  71. }
  72. public string GetValue (int i)
  73. {
  74. return (string) attrValues [i];
  75. }
  76. public string GetValue (string name)
  77. {
  78. for (int i = 0; i < attrNames.Count; i++)
  79. if ((string) attrNames [i] == name)
  80. return (string) attrValues [i];
  81. return null;
  82. }
  83. public string [] Names {
  84. get { return (string []) attrNames.ToArray (typeof (string)); }
  85. }
  86. public string [] Values {
  87. get { return (string []) attrValues.ToArray (typeof (string)); }
  88. }
  89. ArrayList attrNames = new ArrayList ();
  90. ArrayList attrValues = new ArrayList ();
  91. internal void Clear ()
  92. {
  93. attrNames.Clear ();
  94. attrValues.Clear ();
  95. }
  96. internal void Add (string name, string value)
  97. {
  98. attrNames.Add (name);
  99. attrValues.Add (value);
  100. }
  101. }
  102. IContentHandler handler;
  103. TextReader reader;
  104. Stack elementNames = new Stack ();
  105. Stack xmlSpaces = new Stack ();
  106. string xmlSpace;
  107. StringBuilder buffer = new StringBuilder (200);
  108. char [] nameBuffer = new char [30];
  109. bool isWhitespace;
  110. AttrListImpl attributes = new AttrListImpl ();
  111. int line = 1, column;
  112. bool resetColumn;
  113. public SmallXmlParser ()
  114. {
  115. }
  116. private Exception Error (string msg)
  117. {
  118. return new SmallXmlParserException (msg, line, column);
  119. }
  120. private Exception UnexpectedEndError ()
  121. {
  122. string [] arr = new string [elementNames.Count];
  123. // COMPACT FRAMEWORK NOTE: CopyTo is not visible through the Stack class
  124. (elementNames as ICollection).CopyTo (arr, 0);
  125. return Error (String.Format (
  126. "Unexpected end of stream. Element stack content is {0}", String.Join (",", arr)));
  127. }
  128. private bool IsNameChar (char c, bool start)
  129. {
  130. switch (c) {
  131. case ':':
  132. case '_':
  133. return true;
  134. case '-':
  135. case '.':
  136. return !start;
  137. }
  138. if (c > 0x100) { // optional condition for optimization
  139. switch (c) {
  140. case '\u0559':
  141. case '\u06E5':
  142. case '\u06E6':
  143. return true;
  144. }
  145. if ('\u02BB' <= c && c <= '\u02C1')
  146. return true;
  147. }
  148. switch (Char.GetUnicodeCategory (c)) {
  149. case UnicodeCategory.LowercaseLetter:
  150. case UnicodeCategory.UppercaseLetter:
  151. case UnicodeCategory.OtherLetter:
  152. case UnicodeCategory.TitlecaseLetter:
  153. case UnicodeCategory.LetterNumber:
  154. return true;
  155. case UnicodeCategory.SpacingCombiningMark:
  156. case UnicodeCategory.EnclosingMark:
  157. case UnicodeCategory.NonSpacingMark:
  158. case UnicodeCategory.ModifierLetter:
  159. case UnicodeCategory.DecimalDigitNumber:
  160. return !start;
  161. default:
  162. return false;
  163. }
  164. }
  165. private bool IsWhitespace (int c)
  166. {
  167. switch (c) {
  168. case ' ':
  169. case '\r':
  170. case '\t':
  171. case '\n':
  172. return true;
  173. default:
  174. return false;
  175. }
  176. }
  177. public void SkipWhitespaces ()
  178. {
  179. SkipWhitespaces (false);
  180. }
  181. private void HandleWhitespaces ()
  182. {
  183. while (IsWhitespace (Peek ()))
  184. buffer.Append ((char) Read ());
  185. if (Peek () != '<' && Peek () >= 0)
  186. isWhitespace = false;
  187. }
  188. public void SkipWhitespaces (bool expected)
  189. {
  190. while (true) {
  191. switch (Peek ()) {
  192. case ' ':
  193. case '\r':
  194. case '\t':
  195. case '\n':
  196. Read ();
  197. if (expected)
  198. expected = false;
  199. continue;
  200. }
  201. if (expected)
  202. throw Error ("Whitespace is expected.");
  203. return;
  204. }
  205. }
  206. private int Peek ()
  207. {
  208. return reader.Peek ();
  209. }
  210. private int Read ()
  211. {
  212. int i = reader.Read ();
  213. if (i == '\n')
  214. resetColumn = true;
  215. if (resetColumn) {
  216. line++;
  217. resetColumn = false;
  218. column = 1;
  219. }
  220. else
  221. column++;
  222. return i;
  223. }
  224. public void Expect (int c)
  225. {
  226. int p = Read ();
  227. if (p < 0)
  228. throw UnexpectedEndError ();
  229. else if (p != c)
  230. throw Error (String.Format ("Expected '{0}' but got {1}", (char) c, (char) p));
  231. }
  232. private string ReadUntil (char until, bool handleReferences)
  233. {
  234. while (true) {
  235. if (Peek () < 0)
  236. throw UnexpectedEndError ();
  237. char c = (char) Read ();
  238. if (c == until)
  239. break;
  240. else if (handleReferences && c == '&')
  241. ReadReference ();
  242. else
  243. buffer.Append (c);
  244. }
  245. string ret = buffer.ToString ();
  246. buffer.Length = 0;
  247. return ret;
  248. }
  249. public string ReadName ()
  250. {
  251. int idx = 0;
  252. if (Peek () < 0 || !IsNameChar ((char) Peek (), true))
  253. throw Error ("XML name start character is expected.");
  254. for (int i = Peek (); i >= 0; i = Peek ()) {
  255. char c = (char) i;
  256. if (!IsNameChar (c, false))
  257. break;
  258. if (idx == nameBuffer.Length) {
  259. char [] tmp = new char [idx * 2];
  260. // COMPACT FRAMEWORK NOTE: Array.Copy(sourceArray, destinationArray, count) is not available.
  261. Array.Copy (nameBuffer, 0, tmp, 0, idx);
  262. nameBuffer = tmp;
  263. }
  264. nameBuffer [idx++] = c;
  265. Read ();
  266. }
  267. if (idx == 0)
  268. throw Error ("Valid XML name is expected.");
  269. return new string (nameBuffer, 0, idx);
  270. }
  271. public void Parse (TextReader input, IContentHandler handler)
  272. {
  273. this.reader = input;
  274. this.handler = handler;
  275. handler.OnStartParsing (this);
  276. while (Peek () >= 0)
  277. ReadContent ();
  278. HandleBufferedContent ();
  279. if (elementNames.Count > 0)
  280. throw Error (String.Format ("Insufficient close tag: {0}", elementNames.Peek ()));
  281. handler.OnEndParsing (this);
  282. Cleanup ();
  283. }
  284. private void Cleanup ()
  285. {
  286. line = 1;
  287. column = 0;
  288. handler = null;
  289. reader = null;
  290. #if CF_1_0
  291. elementNames = new Stack ();
  292. xmlSpaces = new Stack ();
  293. #else
  294. elementNames.Clear ();
  295. xmlSpaces.Clear ();
  296. #endif
  297. attributes.Clear ();
  298. buffer.Length = 0;
  299. xmlSpace = null;
  300. isWhitespace = false;
  301. }
  302. public void ReadContent ()
  303. {
  304. string name;
  305. if (IsWhitespace (Peek ())) {
  306. if (buffer.Length == 0)
  307. isWhitespace = true;
  308. HandleWhitespaces ();
  309. }
  310. if (Peek () == '<') {
  311. Read ();
  312. switch (Peek ()) {
  313. case '!': // declarations
  314. Read ();
  315. if (Peek () == '[') {
  316. Read ();
  317. if (ReadName () != "CDATA")
  318. throw Error ("Invalid declaration markup");
  319. Expect ('[');
  320. ReadCDATASection ();
  321. return;
  322. }
  323. else if (Peek () == '-') {
  324. ReadComment ();
  325. return;
  326. }
  327. else if (ReadName () != "DOCTYPE")
  328. throw Error ("Invalid declaration markup.");
  329. else
  330. throw Error ("This parser does not support document type.");
  331. case '?': // PIs
  332. HandleBufferedContent ();
  333. Read ();
  334. name = ReadName ();
  335. SkipWhitespaces ();
  336. string text = String.Empty;
  337. if (Peek () != '?') {
  338. while (true) {
  339. text += ReadUntil ('?', false);
  340. if (Peek () == '>')
  341. break;
  342. text += "?";
  343. }
  344. }
  345. handler.OnProcessingInstruction (
  346. name, text);
  347. Expect ('>');
  348. return;
  349. case '/': // end tags
  350. HandleBufferedContent ();
  351. if (elementNames.Count == 0)
  352. throw UnexpectedEndError ();
  353. Read ();
  354. name = ReadName ();
  355. SkipWhitespaces ();
  356. string expected = (string) elementNames.Pop ();
  357. xmlSpaces.Pop ();
  358. if (xmlSpaces.Count > 0)
  359. xmlSpace = (string) xmlSpaces.Peek ();
  360. else
  361. xmlSpace = null;
  362. if (name != expected)
  363. throw Error (String.Format ("End tag mismatch: expected {0} but found {1}", expected, name));
  364. handler.OnEndElement (name);
  365. Expect ('>');
  366. return;
  367. default: // start tags (including empty tags)
  368. HandleBufferedContent ();
  369. name = ReadName ();
  370. while (Peek () != '>' && Peek () != '/')
  371. ReadAttribute (attributes);
  372. handler.OnStartElement (name, attributes);
  373. attributes.Clear ();
  374. SkipWhitespaces ();
  375. if (Peek () == '/') {
  376. Read ();
  377. handler.OnEndElement (name);
  378. }
  379. else {
  380. elementNames.Push (name);
  381. xmlSpaces.Push (xmlSpace);
  382. }
  383. Expect ('>');
  384. return;
  385. }
  386. }
  387. else
  388. ReadCharacters ();
  389. }
  390. private void HandleBufferedContent ()
  391. {
  392. if (buffer.Length == 0)
  393. return;
  394. if (isWhitespace)
  395. handler.OnIgnorableWhitespace (buffer.ToString ());
  396. else
  397. handler.OnChars (buffer.ToString ());
  398. buffer.Length = 0;
  399. isWhitespace = false;
  400. }
  401. private void ReadCharacters ()
  402. {
  403. isWhitespace = false;
  404. while (true) {
  405. int i = Peek ();
  406. switch (i) {
  407. case -1:
  408. return;
  409. case '<':
  410. return;
  411. case '&':
  412. Read ();
  413. ReadReference ();
  414. continue;
  415. default:
  416. buffer.Append ((char) Read ());
  417. continue;
  418. }
  419. }
  420. }
  421. private void ReadReference ()
  422. {
  423. if (Peek () == '#') {
  424. // character reference
  425. Read ();
  426. ReadCharacterReference ();
  427. } else {
  428. string name = ReadName ();
  429. Expect (';');
  430. switch (name) {
  431. case "amp":
  432. buffer.Append ('&');
  433. break;
  434. case "quot":
  435. buffer.Append ('"');
  436. break;
  437. case "apos":
  438. buffer.Append ('\'');
  439. break;
  440. case "lt":
  441. buffer.Append ('<');
  442. break;
  443. case "gt":
  444. buffer.Append ('>');
  445. break;
  446. default:
  447. throw Error ("General non-predefined entity reference is not supported in this parser.");
  448. }
  449. }
  450. }
  451. private int ReadCharacterReference ()
  452. {
  453. int n = 0;
  454. if (Peek () == 'x') { // hex
  455. Read ();
  456. for (int i = Peek (); i >= 0; i = Peek ()) {
  457. if ('0' <= i && i <= '9')
  458. n = n << 4 + i - '0';
  459. else if ('A' <= i && i <='F')
  460. n = n << 4 + i - 'A' + 10;
  461. else if ('a' <= i && i <='f')
  462. n = n << 4 + i - 'a' + 10;
  463. else
  464. break;
  465. Read ();
  466. }
  467. } else {
  468. for (int i = Peek (); i >= 0; i = Peek ()) {
  469. if ('0' <= i && i <= '9')
  470. n = n << 4 + i - '0';
  471. else
  472. break;
  473. Read ();
  474. }
  475. }
  476. return n;
  477. }
  478. private void ReadAttribute (AttrListImpl a)
  479. {
  480. SkipWhitespaces (true);
  481. if (Peek () == '/' || Peek () == '>')
  482. // came here just to spend trailing whitespaces
  483. return;
  484. string name = ReadName ();
  485. string value;
  486. SkipWhitespaces ();
  487. Expect ('=');
  488. SkipWhitespaces ();
  489. switch (Read ()) {
  490. case '\'':
  491. value = ReadUntil ('\'', true);
  492. break;
  493. case '"':
  494. value = ReadUntil ('"', true);
  495. break;
  496. default:
  497. throw Error ("Invalid attribute value markup.");
  498. }
  499. if (name == "xml:space")
  500. xmlSpace = value;
  501. a.Add (name, value);
  502. }
  503. private void ReadCDATASection ()
  504. {
  505. int nBracket = 0;
  506. while (true) {
  507. if (Peek () < 0)
  508. throw UnexpectedEndError ();
  509. char c = (char) Read ();
  510. if (c == ']')
  511. nBracket++;
  512. else if (c == '>' && nBracket > 1) {
  513. for (int i = nBracket; i > 2; i--)
  514. buffer.Append (']');
  515. break;
  516. }
  517. else {
  518. for (int i = 0; i < nBracket; i++)
  519. buffer.Append (']');
  520. nBracket = 0;
  521. buffer.Append (c);
  522. }
  523. }
  524. }
  525. private void ReadComment ()
  526. {
  527. Expect ('-');
  528. Expect ('-');
  529. while (true) {
  530. if (Read () != '-')
  531. continue;
  532. if (Read () != '-')
  533. continue;
  534. if (Read () != '>')
  535. throw Error ("'--' is not allowed inside comment markup.");
  536. break;
  537. }
  538. }
  539. }
  540. internal class SmallXmlParserException : SystemException
  541. {
  542. int line;
  543. int column;
  544. public SmallXmlParserException (string msg, int line, int column)
  545. : base (String.Format ("{0}. At ({1},{2})", msg, line, column))
  546. {
  547. this.line = line;
  548. this.column = column;
  549. }
  550. public int Line {
  551. get { return line; }
  552. }
  553. public int Column {
  554. get { return column; }
  555. }
  556. }
  557. }