xml_parser.cpp 13 KB

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