xml_parser.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. /*************************************************************************/
  2. /* xml_parser.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* http://www.godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* */
  10. /* Permission is hereby granted, free of charge, to any person obtaining */
  11. /* a copy of this software and associated documentation files (the */
  12. /* "Software"), to deal in the Software without restriction, including */
  13. /* without limitation the rights to use, copy, modify, merge, publish, */
  14. /* distribute, sublicense, and/or sell copies of the Software, and to */
  15. /* permit persons to whom the Software is furnished to do so, subject to */
  16. /* the following conditions: */
  17. /* */
  18. /* The above copyright notice and this permission notice shall be */
  19. /* included in all copies or substantial portions of the Software. */
  20. /* */
  21. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  22. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  23. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  24. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  25. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  26. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  27. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  28. /*************************************************************************/
  29. #include "xml_parser.h"
  30. #include "print_string.h"
  31. //#define DEBUG_XML
  32. VARIANT_ENUM_CAST(XMLParser::NodeType);
  33. static bool _equalsn(const CharType *str1, const CharType *str2, int len) {
  34. int i;
  35. for (i = 0; i < len && str1[i] && str2[i]; ++i)
  36. if (str1[i] != str2[i])
  37. return false;
  38. // if one (or both) of the strings was smaller then they
  39. // are only equal if they have the same lenght
  40. return (i == len) || (str1[i] == 0 && str2[i] == 0);
  41. }
  42. String XMLParser::_replace_special_characters(const String &origstr) {
  43. int pos = origstr.find("&");
  44. int oldPos = 0;
  45. if (pos == -1)
  46. return origstr;
  47. String newstr;
  48. while (pos != -1 && pos < origstr.length() - 2) {
  49. // check if it is one of the special characters
  50. int specialChar = -1;
  51. for (int i = 0; i < (int)special_characters.size(); ++i) {
  52. const CharType *p = &origstr[pos] + 1;
  53. if (_equalsn(&special_characters[i][1], p, special_characters[i].length() - 1)) {
  54. specialChar = i;
  55. break;
  56. }
  57. }
  58. if (specialChar != -1) {
  59. newstr += (origstr.substr(oldPos, pos - oldPos));
  60. newstr += (special_characters[specialChar][0]);
  61. pos += special_characters[specialChar].length();
  62. } else {
  63. newstr += (origstr.substr(oldPos, pos - oldPos + 1));
  64. pos += 1;
  65. }
  66. // find next &
  67. oldPos = pos;
  68. pos = origstr.find("&", pos);
  69. }
  70. if (oldPos < origstr.length() - 1)
  71. newstr += (origstr.substr(oldPos, origstr.length() - oldPos));
  72. return newstr;
  73. }
  74. static inline bool _is_white_space(char c) {
  75. return (c == ' ' || c == '\t' || c == '\n' || c == '\r');
  76. }
  77. //! sets the state that text was found. Returns true if set should be set
  78. bool XMLParser::_set_text(char *start, char *end) {
  79. // check if text is more than 2 characters, and if not, check if there is
  80. // only white space, so that this text won't be reported
  81. if (end - start < 3) {
  82. char *p = start;
  83. for (; p != end; ++p)
  84. if (!_is_white_space(*p))
  85. break;
  86. if (p == end)
  87. return false;
  88. }
  89. // set current text to the parsed text, and replace xml special characters
  90. String s = String::utf8(start, (int)(end - start));
  91. node_name = _replace_special_characters(s);
  92. // current XML node type is text
  93. node_type = NODE_TEXT;
  94. return true;
  95. }
  96. void XMLParser::_parse_closing_xml_element() {
  97. node_type = NODE_ELEMENT_END;
  98. node_empty = false;
  99. attributes.clear();
  100. ++P;
  101. const char *pBeginClose = P;
  102. while (*P != '>')
  103. ++P;
  104. node_name = String::utf8(pBeginClose, (int)(P - pBeginClose));
  105. #ifdef DEBUG_XML
  106. print_line("XML CLOSE: " + node_name);
  107. #endif
  108. ++P;
  109. }
  110. void XMLParser::_ignore_definition() {
  111. node_type = NODE_UNKNOWN;
  112. char *F = P;
  113. // move until end marked with '>' reached
  114. while (*P != '>')
  115. ++P;
  116. node_name.parse_utf8(F, P - F);
  117. ++P;
  118. }
  119. bool XMLParser::_parse_cdata() {
  120. if (*(P + 1) != '[')
  121. return false;
  122. node_type = NODE_CDATA;
  123. // skip '<![CDATA['
  124. int count = 0;
  125. while (*P && count < 8) {
  126. ++P;
  127. ++count;
  128. }
  129. if (!*P)
  130. return true;
  131. char *cDataBegin = P;
  132. char *cDataEnd = 0;
  133. // find end of CDATA
  134. while (*P && !cDataEnd) {
  135. if (*P == '>' &&
  136. (*(P - 1) == ']') &&
  137. (*(P - 2) == ']')) {
  138. cDataEnd = P - 2;
  139. }
  140. ++P;
  141. }
  142. if (cDataEnd)
  143. node_name = String::utf8(cDataBegin, (int)(cDataEnd - cDataBegin));
  144. else
  145. node_name = "";
  146. #ifdef DEBUG_XML
  147. print_line("XML CDATA: " + node_name);
  148. #endif
  149. return true;
  150. }
  151. void XMLParser::_parse_comment() {
  152. node_type = NODE_COMMENT;
  153. P += 1;
  154. char *pCommentBegin = P;
  155. int count = 1;
  156. // move until end of comment reached
  157. while (count) {
  158. if (*P == '>')
  159. --count;
  160. else if (*P == '<')
  161. ++count;
  162. ++P;
  163. }
  164. P -= 3;
  165. node_name = String::utf8(pCommentBegin + 2, (int)(P - pCommentBegin - 2));
  166. P += 3;
  167. #ifdef DEBUG_XML
  168. print_line("XML COMMENT: " + node_name);
  169. #endif
  170. }
  171. void XMLParser::_parse_opening_xml_element() {
  172. node_type = NODE_ELEMENT;
  173. node_empty = false;
  174. attributes.clear();
  175. // find name
  176. const char *startName = P;
  177. // find end of element
  178. while (*P != '>' && !_is_white_space(*P))
  179. ++P;
  180. const char *endName = P;
  181. // find attributes
  182. while (*P != '>') {
  183. if (_is_white_space(*P))
  184. ++P;
  185. else {
  186. if (*P != '/') {
  187. // we've got an attribute
  188. // read the attribute names
  189. const char *attributeNameBegin = P;
  190. while (!_is_white_space(*P) && *P != '=')
  191. ++P;
  192. const char *attributeNameEnd = P;
  193. ++P;
  194. // read the attribute value
  195. // check for quotes and single quotes, thx to murphy
  196. while ((*P != '\"') && (*P != '\'') && *P)
  197. ++P;
  198. if (!*P) // malformatted xml file
  199. return;
  200. const char attributeQuoteChar = *P;
  201. ++P;
  202. const char *attributeValueBegin = P;
  203. while (*P != attributeQuoteChar && *P)
  204. ++P;
  205. if (!*P) // malformatted xml file
  206. return;
  207. const char *attributeValueEnd = P;
  208. ++P;
  209. Attribute attr;
  210. attr.name = String::utf8(attributeNameBegin,
  211. (int)(attributeNameEnd - attributeNameBegin));
  212. String s = String::utf8(attributeValueBegin,
  213. (int)(attributeValueEnd - attributeValueBegin));
  214. attr.value = _replace_special_characters(s);
  215. attributes.push_back(attr);
  216. } else {
  217. // tag is closed directly
  218. ++P;
  219. node_empty = true;
  220. break;
  221. }
  222. }
  223. }
  224. // check if this tag is closing directly
  225. if (endName > startName && *(endName - 1) == '/') {
  226. // directly closing tag
  227. node_empty = true;
  228. endName--;
  229. }
  230. node_name = String::utf8(startName, (int)(endName - startName));
  231. #ifdef DEBUG_XML
  232. print_line("XML OPEN: " + node_name);
  233. #endif
  234. ++P;
  235. }
  236. void XMLParser::_parse_current_node() {
  237. char *start = P;
  238. node_offset = P - data;
  239. // more forward until '<' found
  240. while (*P != '<' && *P)
  241. ++P;
  242. if (!*P)
  243. return;
  244. if (P - start > 0) {
  245. // we found some text, store it
  246. if (_set_text(start, P))
  247. return;
  248. }
  249. ++P;
  250. // based on current token, parse and report next element
  251. switch (*P) {
  252. case '/':
  253. _parse_closing_xml_element();
  254. break;
  255. case '?':
  256. _ignore_definition();
  257. break;
  258. case '!':
  259. if (!_parse_cdata())
  260. _parse_comment();
  261. break;
  262. default:
  263. _parse_opening_xml_element();
  264. break;
  265. }
  266. }
  267. uint64_t XMLParser::get_node_offset() const {
  268. return node_offset;
  269. };
  270. Error XMLParser::seek(uint64_t p_pos) {
  271. ERR_FAIL_COND_V(!data, ERR_FILE_EOF)
  272. ERR_FAIL_COND_V(p_pos >= length, ERR_FILE_EOF);
  273. P = data + p_pos;
  274. return read();
  275. };
  276. void XMLParser::_bind_methods() {
  277. ObjectTypeDB::bind_method(_MD("read"), &XMLParser::read);
  278. ObjectTypeDB::bind_method(_MD("get_node_type"), &XMLParser::get_node_type);
  279. ObjectTypeDB::bind_method(_MD("get_node_name"), &XMLParser::get_node_name);
  280. ObjectTypeDB::bind_method(_MD("get_node_data"), &XMLParser::get_node_data);
  281. ObjectTypeDB::bind_method(_MD("get_node_offset"), &XMLParser::get_node_offset);
  282. ObjectTypeDB::bind_method(_MD("get_attribute_count"), &XMLParser::get_attribute_count);
  283. ObjectTypeDB::bind_method(_MD("get_attribute_name", "idx"), &XMLParser::get_attribute_name);
  284. ObjectTypeDB::bind_method(_MD("get_attribute_value", "idx"), (String(XMLParser::*)(int) const) & XMLParser::get_attribute_value);
  285. ObjectTypeDB::bind_method(_MD("has_attribute", "name"), &XMLParser::has_attribute);
  286. ObjectTypeDB::bind_method(_MD("get_named_attribute_value", "name"), (String(XMLParser::*)(const String &) const) & XMLParser::get_attribute_value);
  287. ObjectTypeDB::bind_method(_MD("get_named_attribute_value_safe", "name"), &XMLParser::get_attribute_value_safe);
  288. ObjectTypeDB::bind_method(_MD("is_empty"), &XMLParser::is_empty);
  289. ObjectTypeDB::bind_method(_MD("get_current_line"), &XMLParser::get_current_line);
  290. ObjectTypeDB::bind_method(_MD("skip_section"), &XMLParser::skip_section);
  291. ObjectTypeDB::bind_method(_MD("seek", "pos"), &XMLParser::seek);
  292. ObjectTypeDB::bind_method(_MD("open", "file"), &XMLParser::open);
  293. ObjectTypeDB::bind_method(_MD("open_buffer", "buffer"), &XMLParser::open_buffer);
  294. BIND_CONSTANT(NODE_NONE);
  295. BIND_CONSTANT(NODE_ELEMENT);
  296. BIND_CONSTANT(NODE_ELEMENT_END);
  297. BIND_CONSTANT(NODE_TEXT);
  298. BIND_CONSTANT(NODE_COMMENT);
  299. BIND_CONSTANT(NODE_CDATA);
  300. BIND_CONSTANT(NODE_UNKNOWN);
  301. };
  302. Error XMLParser::read() {
  303. // if not end reached, parse the node
  304. if (P && (P - data) < length - 1 && *P != 0) {
  305. _parse_current_node();
  306. return OK;
  307. }
  308. return ERR_FILE_EOF;
  309. }
  310. XMLParser::NodeType XMLParser::get_node_type() {
  311. return node_type;
  312. }
  313. String XMLParser::get_node_data() const {
  314. ERR_FAIL_COND_V(node_type != NODE_TEXT, "");
  315. return node_name;
  316. }
  317. String XMLParser::get_node_name() const {
  318. ERR_FAIL_COND_V(node_type == NODE_TEXT, "");
  319. return node_name;
  320. }
  321. int XMLParser::get_attribute_count() const {
  322. return attributes.size();
  323. }
  324. String XMLParser::get_attribute_name(int p_idx) const {
  325. ERR_FAIL_INDEX_V(p_idx, attributes.size(), "");
  326. return attributes[p_idx].name;
  327. }
  328. String XMLParser::get_attribute_value(int p_idx) const {
  329. ERR_FAIL_INDEX_V(p_idx, attributes.size(), "");
  330. return attributes[p_idx].value;
  331. }
  332. bool XMLParser::has_attribute(const String &p_name) const {
  333. for (int i = 0; i < attributes.size(); i++) {
  334. if (attributes[i].name == p_name)
  335. return true;
  336. }
  337. return false;
  338. }
  339. String XMLParser::get_attribute_value(const String &p_name) const {
  340. int idx = -1;
  341. for (int i = 0; i < attributes.size(); i++) {
  342. if (attributes[i].name == p_name) {
  343. idx = i;
  344. break;
  345. }
  346. }
  347. if (idx < 0) {
  348. ERR_EXPLAIN("Attribute not found: " + p_name);
  349. }
  350. ERR_FAIL_COND_V(idx < 0, "");
  351. return attributes[idx].value;
  352. }
  353. String XMLParser::get_attribute_value_safe(const String &p_name) const {
  354. int idx = -1;
  355. for (int i = 0; i < attributes.size(); i++) {
  356. if (attributes[i].name == p_name) {
  357. idx = i;
  358. break;
  359. }
  360. }
  361. if (idx < 0)
  362. return "";
  363. return attributes[idx].value;
  364. }
  365. bool XMLParser::is_empty() const {
  366. return node_empty;
  367. }
  368. Error XMLParser::open_buffer(const Vector<uint8_t> &p_buffer) {
  369. ERR_FAIL_COND_V(p_buffer.size() == 0, ERR_INVALID_DATA);
  370. length = p_buffer.size();
  371. data = memnew_arr(char, length + 1);
  372. copymem(data, p_buffer.ptr(), length);
  373. data[length] = 0;
  374. P = data;
  375. return OK;
  376. }
  377. Error XMLParser::open(const String &p_path) {
  378. Error err;
  379. FileAccess *file = FileAccess::open(p_path, FileAccess::READ, &err);
  380. if (err) {
  381. ERR_FAIL_COND_V(err != OK, err);
  382. }
  383. length = file->get_len();
  384. ERR_FAIL_COND_V(length < 1, ERR_FILE_CORRUPT);
  385. data = memnew_arr(char, length + 1);
  386. file->get_buffer((uint8_t *)data, length);
  387. data[length] = 0;
  388. P = data;
  389. memdelete(file);
  390. return OK;
  391. }
  392. void XMLParser::skip_section() {
  393. // skip if this element is empty anyway.
  394. if (is_empty())
  395. return;
  396. // read until we've reached the last element in this section
  397. int tagcount = 1;
  398. while (tagcount && read() == OK) {
  399. if (get_node_type() == XMLParser::NODE_ELEMENT &&
  400. !is_empty()) {
  401. ++tagcount;
  402. } else if (get_node_type() == XMLParser::NODE_ELEMENT_END)
  403. --tagcount;
  404. }
  405. }
  406. void XMLParser::close() {
  407. if (data)
  408. memdelete_arr(data);
  409. data = NULL;
  410. length = 0;
  411. P = NULL;
  412. node_empty = false;
  413. node_type = NODE_NONE;
  414. node_offset = 0;
  415. }
  416. int XMLParser::get_current_line() const {
  417. return 0;
  418. }
  419. XMLParser::XMLParser() {
  420. data = NULL;
  421. close();
  422. special_characters.push_back("&amp;");
  423. special_characters.push_back("<lt;");
  424. special_characters.push_back(">gt;");
  425. special_characters.push_back("\"quot;");
  426. special_characters.push_back("'apos;");
  427. }
  428. XMLParser::~XMLParser() {
  429. if (data)
  430. memdelete_arr(data);
  431. }