SmallXmlParser.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. // TODO: Put this in a vendor folder, DLL, etc.
  32. using System;
  33. using System.Collections;
  34. using System.Collections.Generic;
  35. using System.Globalization;
  36. using System.IO;
  37. using System.Text;
  38. public class SmallXmlParser {
  39. public interface IContentHandler {
  40. void OnStartParsing(SmallXmlParser parser);
  41. void OnStartElement(string name, Dictionary<string, string> attrs);
  42. void OnEndElement(string name);
  43. void OnInlineElement(string name, Dictionary<string, string> attrs);
  44. }
  45. private IContentHandler handler;
  46. private TextReader reader;
  47. private readonly LiteStack<string> elementNames = new LiteStack<string>();
  48. private readonly StringBuilder buffer = new StringBuilder(200);
  49. private char[] nameBuffer = new char[30];
  50. private Dictionary<string, string> attributes = new Dictionary<string, string>();
  51. private int line = 1, column;
  52. private bool resetColumn;
  53. private Exception Error(string msg) {
  54. return new SmallXmlParserException(msg, line, column);
  55. }
  56. private Exception UnexpectedEndError() {
  57. string[] arr = new string[elementNames.Count];
  58. // COMPACT FRAMEWORK NOTE: CopyTo is not visible through the Stack class
  59. (elementNames as ICollection).CopyTo(arr, 0);
  60. return Error(String.Format("Unexpected end of stream. Element stack content is {0}",
  61. String.Join(",", arr)));
  62. }
  63. private bool IsNameChar(char c, bool start) {
  64. switch(c) {
  65. case ':':
  66. case '_':
  67. return true;
  68. case '-':
  69. case '.':
  70. return !start;
  71. }
  72. if(c > 0x100) {
  73. // optional condition for optimization
  74. switch(c) {
  75. case '\u0559':
  76. case '\u06E5':
  77. case '\u06E6':
  78. return true;
  79. }
  80. if('\u02BB' <= c && c <= '\u02C1')
  81. return true;
  82. }
  83. switch(Char.GetUnicodeCategory(c)) {
  84. case UnicodeCategory.LowercaseLetter:
  85. case UnicodeCategory.UppercaseLetter:
  86. case UnicodeCategory.OtherLetter:
  87. case UnicodeCategory.TitlecaseLetter:
  88. case UnicodeCategory.LetterNumber:
  89. return true;
  90. case UnicodeCategory.SpacingCombiningMark:
  91. case UnicodeCategory.EnclosingMark:
  92. case UnicodeCategory.NonSpacingMark:
  93. case UnicodeCategory.ModifierLetter:
  94. case UnicodeCategory.DecimalDigitNumber:
  95. return !start;
  96. default:
  97. return false;
  98. }
  99. }
  100. private bool IsWhitespace(int c) {
  101. switch(c) {
  102. case ' ':
  103. case '\r':
  104. case '\t':
  105. case '\n':
  106. return true;
  107. default:
  108. return false;
  109. }
  110. }
  111. public void SkipWhitespaces() {
  112. SkipWhitespaces(false);
  113. }
  114. private void HandleWhitespaces() {
  115. while(IsWhitespace(Peek()))
  116. buffer.Append((char)Read());
  117. }
  118. public void SkipWhitespaces(bool expected) {
  119. while(true) {
  120. switch(Peek()) {
  121. case ' ':
  122. case '\r':
  123. case '\t':
  124. case '\n':
  125. Read();
  126. if(expected)
  127. expected = false;
  128. continue;
  129. }
  130. if(expected)
  131. throw Error("Whitespace is expected.");
  132. return;
  133. }
  134. }
  135. private int Peek() {
  136. return reader.Peek();
  137. }
  138. private int Read() {
  139. int i = reader.Read();
  140. if(i == '\n')
  141. resetColumn = true;
  142. if(resetColumn) {
  143. line++;
  144. resetColumn = false;
  145. column = 1;
  146. } else
  147. column++;
  148. return i;
  149. }
  150. public void Expect(int c) {
  151. int p = Read();
  152. if(p < 0)
  153. throw UnexpectedEndError();
  154. else if(p != c)
  155. throw Error(String.Format("Expected '{0}' but got {1}", (char)c, (char)p));
  156. }
  157. private string ReadUntil(char until, bool handleReferences) {
  158. while(true) {
  159. if(Peek() < 0)
  160. throw UnexpectedEndError();
  161. char c = (char)Read();
  162. if(c == until)
  163. break;
  164. else if(handleReferences && c == '&')
  165. ReadReference();
  166. else
  167. buffer.Append(c);
  168. }
  169. string ret = buffer.ToString();
  170. buffer.Length = 0;
  171. return ret;
  172. }
  173. public string ReadName() {
  174. int idx = 0;
  175. if(Peek() < 0 || !IsNameChar((char)Peek(), true))
  176. throw Error("XML name start character is expected.");
  177. for(int i = Peek(); i >= 0; i = Peek()) {
  178. char c = (char)i;
  179. if(!IsNameChar(c, false))
  180. break;
  181. if(idx == nameBuffer.Length) {
  182. char[] tmp = new char[idx * 2];
  183. // COMPACT FRAMEWORK NOTE: Array.Copy(sourceArray, destinationArray, count) is not available.
  184. Array.Copy(nameBuffer, 0, tmp, 0, idx);
  185. nameBuffer = tmp;
  186. }
  187. nameBuffer[idx++] = c;
  188. Read();
  189. }
  190. if(idx == 0)
  191. throw Error("Valid XML name is expected.");
  192. return new string(nameBuffer, 0, idx);
  193. }
  194. public void Parse(TextReader input, IContentHandler handler) {
  195. this.reader = input;
  196. this.handler = handler;
  197. handler.OnStartParsing(this);
  198. while(Peek() >= 0)
  199. ReadContent();
  200. buffer.Length = 0;
  201. if(elementNames.Count > 0)
  202. throw Error(String.Format("Insufficient close tag: {0}", elementNames.Peek()));
  203. Cleanup();
  204. }
  205. private void Cleanup() {
  206. line = 1;
  207. column = 0;
  208. handler = null;
  209. reader = null;
  210. elementNames.Clear();
  211. attributes.Clear();
  212. buffer.Length = 0;
  213. }
  214. public void ReadContent() {
  215. string name;
  216. if(IsWhitespace(Peek()))
  217. HandleWhitespaces();
  218. if(Peek() == '<') {
  219. Read();
  220. switch(Peek()) {
  221. case '!': // declarations
  222. Read();
  223. if(Peek() == '[') {
  224. Read();
  225. if(ReadName() != "CDATA")
  226. throw Error("Invalid declaration markup");
  227. Expect('[');
  228. ReadCDATASection();
  229. return;
  230. } else if(Peek() == '-') {
  231. ReadComment();
  232. return;
  233. } else if(ReadName() != "DOCTYPE")
  234. throw Error("Invalid declaration markup.");
  235. else {
  236. ReadUntil('>', false);
  237. return;
  238. }
  239. case '?': // PIs
  240. buffer.Length = 0;
  241. Read();
  242. name = ReadName();
  243. SkipWhitespaces();
  244. string text = String.Empty;
  245. if(Peek() != '?') {
  246. while(true) {
  247. text += ReadUntil('?', false);
  248. if(Peek() == '>')
  249. break;
  250. text += "?";
  251. }
  252. }
  253. Expect('>');
  254. return;
  255. case '/': // end tags
  256. buffer.Length = 0;
  257. if(elementNames.Count == 0)
  258. throw UnexpectedEndError();
  259. Read();
  260. name = ReadName();
  261. SkipWhitespaces();
  262. string expected = (string)elementNames.Pop();
  263. if(name != expected)
  264. throw Error(String.Format("End tag mismatch: expected {0} but found {1}", expected, name));
  265. handler.OnEndElement(name);
  266. Expect('>');
  267. return;
  268. default: // start tags (including empty tags)
  269. buffer.Length = 0;
  270. name = ReadName();
  271. while(Peek() != '>' && Peek() != '/')
  272. ReadAttribute(attributes);
  273. SkipWhitespaces();
  274. if(Peek() == '/') {
  275. handler.OnInlineElement(name, attributes);
  276. Read();
  277. } else {
  278. handler.OnStartElement(name, attributes);
  279. elementNames.Push(name);
  280. }
  281. attributes.Clear();
  282. Expect('>');
  283. return;
  284. }
  285. } else
  286. ReadCharacters();
  287. }
  288. private void ReadCharacters() {
  289. while(true) {
  290. int i = Peek();
  291. switch(i) {
  292. case -1:
  293. return;
  294. case '<':
  295. return;
  296. case '&':
  297. Read();
  298. ReadReference();
  299. continue;
  300. default:
  301. buffer.Append((char)Read());
  302. continue;
  303. }
  304. }
  305. }
  306. private void ReadReference() {
  307. if(Peek() == '#') {
  308. // character reference
  309. Read();
  310. ReadCharacterReference();
  311. } else {
  312. string name = ReadName();
  313. Expect(';');
  314. switch(name) {
  315. case "amp": buffer.Append('&'); break;
  316. case "quot": buffer.Append('"'); break;
  317. case "apos": buffer.Append('\''); break;
  318. case "lt": buffer.Append('<'); break;
  319. case "gt": buffer.Append('>'); break;
  320. default: throw Error("General non-predefined entity reference is not supported in this parser.");
  321. }
  322. }
  323. }
  324. private int ReadCharacterReference() {
  325. int n = 0;
  326. if(Peek() == 'x') {
  327. // hex
  328. Read();
  329. for(int i = Peek(); i >= 0; i = Peek()) {
  330. if('0' <= i && i <= '9') n = n << 4 + i - '0';
  331. else if('A' <= i && i <= 'F') n = n << 4 + i - 'A' + 10;
  332. else if('a' <= i && i <= 'f') n = n << 4 + i - 'a' + 10;
  333. else break;
  334. Read();
  335. }
  336. } else {
  337. for(int i = Peek(); i >= 0; i = Peek()) {
  338. if('0' <= i && i <= '9')
  339. n = n << 4 + i - '0';
  340. else
  341. break;
  342. Read();
  343. }
  344. }
  345. return n;
  346. }
  347. private void ReadAttribute(Dictionary<string, string> a) {
  348. SkipWhitespaces(true);
  349. if(Peek() == '/' || Peek() == '>')
  350. // came here just to spend trailing whitespaces
  351. return;
  352. string name = ReadName();
  353. string value;
  354. SkipWhitespaces();
  355. Expect('=');
  356. SkipWhitespaces();
  357. switch(Read()) {
  358. case '\'': value = ReadUntil('\'', true); break;
  359. case '"': value = ReadUntil('"', true); break;
  360. default: throw Error("Invalid attribute value markup.");
  361. }
  362. a.Add(name, value);
  363. }
  364. private void ReadCDATASection() {
  365. int nBracket = 0;
  366. while(true) {
  367. if(Peek() < 0)
  368. throw UnexpectedEndError();
  369. char c = (char)Read();
  370. if(c == ']')
  371. nBracket++;
  372. else if(c == '>' && nBracket > 1) {
  373. for(int i = nBracket; i > 2; i--)
  374. buffer.Append(']');
  375. break;
  376. } else {
  377. for(int i = 0; i < nBracket; i++)
  378. buffer.Append(']');
  379. nBracket = 0;
  380. buffer.Append(c);
  381. }
  382. }
  383. }
  384. private void ReadComment() {
  385. Expect('-');
  386. Expect('-');
  387. while(true) {
  388. if(Read() != '-') continue;
  389. if(Read() != '-') continue;
  390. if(Read() != '>') throw Error("'--' is not allowed inside comment markup.");
  391. break;
  392. }
  393. }
  394. }
  395. internal sealed class SmallXmlParserException : SystemException {
  396. private readonly int line;
  397. private readonly int column;
  398. public SmallXmlParserException(string msg, int line, int column)
  399. : base(String.Format("{0}. At ({1},{2})", msg, line, column)) {
  400. this.line = line;
  401. this.column = column;
  402. }
  403. public int Line { get { return line; } }
  404. public int Column { get { return column; } }
  405. }